问题
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".
This is my code:
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....");
}
}
}
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.
回答1:
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....");
}
}
}
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/28729707/incompatible-types-void-cannot-be-converted-to-int