【问题标题】:incompatible types: void cannot be converted to int [duplicate]不兼容的类型:void 不能转换为 int [重复]
【发布时间】:2015-04-28 01:51:54
【问题描述】:

我对 Java 和一般编程非常陌生。我正在尝试创建一个简单的程序,您可以在其中猜出我的年龄,如果您是对的,它将说“正确”,如果您错了,它将说“错误”。

这是我的代码:

import java.util.InputMismatchException;
import java.util.Scanner; // This will import just the Scanner class.

public class GuessAge {
    public static int main(int[] args) {
       System.out.println("\nWhat is David's Age?");
       Scanner userInputScanner = new Scanner(System.in);
       int age = userInputScanner.nextLine();



        int validInput = 20;
        if (validInput == 20) {
            return System.out.println("Correct!!");
        }
        else {
            return System.out.println("Wrong....");
        }
    }
}

我收到错误“不兼容的类型:void 无法转换为 int”,但代码中没有 void 类?我知道我的代码可能很糟糕,但如果你们能指出我正确的方向,那就太好了。谢谢。

【问题讨论】:

    标签: java class void


    【解决方案1】:

    您的程序不必在public static int main 中返回int。相反,您可以将其命名为void(意味着不返回任何内容)。你应该只是打印你的陈述而不是return他们。 int[] 也应该是 String[]Scanner 应该检查 nextInt() 在 cmets 中指出!

    import java.util.InputMismatchException;
    import java.util.Scanner; // This will import just the Scanner class.
    
    public class GuessAge {
    public static void main(String[] args) {
       System.out.println("\nWhat is David's Age?");
       Scanner userInputScanner = new Scanner(System.in);
       int age = userInputScanner.nextInt();
    
    
    
        int validInput = 20;
    
        // typo in your code - compare to age
        if (validInput == age) {
            System.out.println("Correct!!");
        }
        else {
            System.out.println("Wrong....");
        }
    }
    
    }
    

    【讨论】:

    • int age = userInputScanner.nextLine(); 看起来也有点奇怪。
    • 你的权利 - 代码需要更好的重构。两秒
    • nextInt() 会更好
    • 更新了答案!
    • 谢谢 Germaine 和其他所有人!非常有帮助。我让它工作了!太棒了。
    【解决方案2】:

    您正在尝试返回System.out.println(),它的类型为void。从System.out.println() 之前删除return 语句,它们仍然会打印。请注意,您不需要在 main 方法中指定返回值。

    【讨论】:

    • 另外,在您的 if 语句中,您将 validInput 与 20 进行比较,因为您将其初始化为 20,所以这是正确的。您希望将 age 与 20 进行比较。
    • @not_a_bot 将您的修复添加到我的答案中 - 好电话!
    • 谢谢!我取出了返回语句并在 if 语句中切换了有效输入,但我仍然收到最后一个错误,说字符串无法转换为 int,然后 cmd 提示符说显示这一行 int age = userInputScanner.nextline();
    • @javanoob 看看我的完整答案
    【解决方案3】:

    在你的方法声明中,你有public static int main(int[] args)

    static 关键字后面的单词是返回类型,在这种情况下,您的声明要求 main 方法返回 int。为了解决这个问题,main 应该有一个 void 返回类型,因为你只在 main 中打印而不返回 int 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 2018-12-02
      • 1970-01-01
      • 2017-07-11
      相关资源
      最近更新 更多