So im learning java,bit by bit im getting a bit more knowledge, now im following tutroials and other webistes ect on learning but im stuck on one problem where i can't figure out what's the problem.
import java.util.Scanner;
class apples{
public static void main(String args[]){
System.out.print("Player Name?");
Scanner name = new Scanner(System.in);
System.out.print(name.nextLine());
System.out.print(" ,how old are you?");
Scanner age = new Scanner(System.in);
System.out.print(age.nextLine());
if (age >= 15){
System.out.println("welcome to Azura World");
}else{
System.out.println("insufficient experience");
}
}
}
from what this should do is,ask the player name, one i type that it should ask name, how old are you? with that at hand, i have the age of the input, there for i want to use it in a if statement but its not working i don't understand why. so please explain if have time.
Also im using THIS as a guide for now
This is because java is statically-typed and
Scanner
'sreadLine
method returns a String, AString
is not anint
or anInteger
and as such cannot be compared with anint
or anInteger
. You need to 'cast' the returned value to anInteger
to be able to compare it with an int, using either Paras Mittal or suchit solutions (I'd personnaly go for Paras solution as it uses nativeScanner
functionality).This adds some difficulties, because you now have to handle the case where the user didn't provide you with an '
Integer
-like' answer (As you would ultimately have to with your actual code, it just doesn't show up for now). In such case, readLine will throw anInputMismatchException
which you have at least two ways to deal with (there may be more depending on your imagination):RuntimeException
, you could just ignore it and let it blow at your user, or whoever is the consumer of your methodage.nextInt();
with atry...catch
clause and then do whatever is significant to your use case (ignore it and set clever default for that value, ask again to the user), You could also preemptively test that user input can be cast into an Integer or keep asking.