#(new to java) i need some help here
1 messages ยท Page 1 of 1 (latest)
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
Here is an AI assisted attempt to answer your question ๐ค. Maybe it helps! In any case, a human is on the way ๐. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
if (scanner.hasNextInt()) {
int num = scanner.nextInt();
System.out.println("You entered: " + num);
} else {
System.out.println("Here");
}
}
}
See, referring from the documentation.
Whenever it gets any value that's not a number it raises java.util.InputMismatchException, you can use a try/catch block to try to input and do something when the InputMismatchException is caught.
It gave you a solution which checks if the nextToken that it'll retrieve on doing nextInt() is actually an int,
The hasNextInt() method returns a boolean indicating if the input entered was an integer.
From the docs^
System.out.println("Input should be a number not text, Try again: ");
so in java the easiest way is to do a try { Integer.parseInt(age) } catch (NumberFormatException e) {}
a more complex is to do a regex match on digits
No, the hasNextInt() method is just for that.
that's wrong, as OP is getting input from a scanner. In the condition the input isn't a valid integer, it'll raise an exception at that part and it would not reach at your code fragment.
ah, ye haddnt seen using the hasNextInt, not a common one to use ๐
Well they can use scanner.next() to store input in a string variable then do your logic but that'll be undoubtedly more complex.
its a problem with having been with java for so long in trivialising these problems when you first start
I didn't get you, what are you trying to say?
just that if you work with java for many years, a lot of things apear simple but are still complex to those learning the language