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'sreadLinemethod returns a String, AStringis not anintor anIntegerand as such cannot be compared with anintor anInteger. You need to 'cast' the returned value to anIntegerto 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 nativeScannerfunctionality).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 anInputMismatchExceptionwhich 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...catchclause 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.