incompatible types: void cannot be converted to int [duplicate]

为君一笑 提交于 2019-11-28 14:23:29

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

}

You are trying to return System.out.println() which is of type void. Remove the return statements from before System.out.println(), and they will still print. Note that you do not need to specify a return value in the main method.

In your method declaration, you have public static int main(int[] args)

The word after the static keyword is a return type, and in this case your declaration is requiring the main method to return an int. To solve this, main should have a void return type, as you're only printing within main and not returning type int.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!