错误:此处不允许使用“void"类型 [英] Error: 'void' type not allowed here

查看:76
本文介绍了错误:此处不允许使用“void"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习使用课程,我的部分任务是制作这个 Car 课程.我在第 6 行遇到错误,我尝试打印类中方法的结果.我认为这意味着我试图打印一些不存在的东西,我怀疑这是里程方法.我尝试更改它以返回里程,但这也不起作用.有什么想法吗?

I'm learning to use classes and part of my assignment is to make this Car class. I'm getting an error on line 6 where I attempt to print of the results of the methods within the class. I think this means that I'm attempting to print something that doesn't exist and I suspect it's the mileage method. I tried changing it to return miles, but that didn't work either. Any ideas?

public class TestCar {
  public static final void main(String args[]) {

    Car c = new Car ();
    c.moveForward(4);
    System.out.println ("The car went" + c.mileage() + "miles."); // <-- L6
  }
}

class Car {
  public int miles = 2000;
  public void moveForward(int mf) {
    if (miles != 2000) {
        miles += mf;
    }
  }

  public void mileage() {
    System.out.print(miles);
  }
}

推荐答案

错误消息准确地告诉您出了什么问题 -- 您正试图从不返回结果的方法中提取结果.

The error message is telling you exactly what is wrong -- you're trying to extract a result from a method that does not return a result.

相反,让 mileage() 方法返回一个字符串,而不是打印出一个字符串.

Instead, have the mileage() method return a String, not print out a String.

public String mileage() {
    return String.valueOf(miles);
}

我自己,我会把它变成一个 getter 方法,而是这样做:

Myself, I'd make this a getter method, and instead would do:

public int getMiles() {
    return miles;
}

这篇关于错误:此处不允许使用“void"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆