#(new to java) i need some help here

1 messages ยท Page 1 of 1 (latest)

fiery windBOT
#

<@&987246399047479336> please have a look, thanks.

fiery windBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

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");
}
}
}

wide jewel
#

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^

sick spoke
#

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

wide jewel
wide jewel
sick spoke
#

ah, ye haddnt seen using the hasNextInt, not a common one to use ๐Ÿ™‚

wide jewel
#

Well they can use scanner.next() to store input in a string variable then do your logic but that'll be undoubtedly more complex.

sick spoke
wide jewel
sick spoke