This question already has an answer here:
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.
You are trying to return
System.out.println()
which is of typevoid
. Remove thereturn
statements from beforeSystem.out.println()
, and they will still print. Note that you do not need to specify a return value in themain
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 anint
. To solve this, main should have a void return type, as you're only printing within main and not returning type int.Your program does not have to return an
int
inpublic static int main
. Instead you can have it asvoid
(meaning don't return anything). You should simply just print your statements and don'treturn
them. Also theint[]
should beString[]
andScanner
should check fornextInt()
as pointed out in comments!