不兼容的类型:void不能转换为int [英] incompatible types: void cannot be converted to int

查看:2621
本文介绍了不兼容的类型:void不能转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我谈到Java和一般的编程时,我是非常新的。我试图创建一个简单的程序,你猜你的年龄,如果你是正确的,它会说正确,如果你错了,它会说错误。

I'm extremely new when to comes to Java and programming in general. I am trying to create a simple program where you guess my age and if you are right it will say "correct" and if you are wrong it will say "wrong".

这是我的代码:

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....");
        }
    }
}

types:void不能转换为int但我在代码中没有void类?我知道我的代码可能是可怕的,但如果你们可以指出我的方向是正确的。谢谢。

I get the error "incompatible types: void cannot be converted to int" but I have no void class in the code? I know my code is probably awful but if you guys could point me in the right direction that would be great. Thanks.

推荐答案

您的程序不必在 int c $ c> public static int main 。相反,你可以有 void (意味着不返回任何东西)。你应该只打印你的语句,不要 return 。此外, int [] 应为 String [] 扫描程序应该检查注释中指出的 nextInt()

Your program does not have to return an int in public static int main. Instead you can have it as void (meaning don't return anything). You should simply just print your statements and don't return them. Also the int[] should be String[] and Scanner should check for nextInt() as pointed out in comments!

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....");
    }
}

}

这篇关于不兼容的类型:void不能转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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