public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println ("Determine if the digit 10 and the digit 1 are the same."");
System.out.println ("Enter 0 to stop";
System.out.print("Enter a 2-digit integer from 10 to 99>>");
Integer num = null;
while (true) {
try{
num = scanner.nextInt();
}catch(Exception e){
System.out.print ("Invalid input". Please re-enter.>>");
}finally {
if (num == 0)
break;
else if ((num < 10) || (num > 99)) {
System.out.print ("Not a two-digit integer") Please re-enter.>>");
}else {
if (num % 10 == num / 10) {
System.out.println ("Yes! 10 and 1 are equal");
System.out.print("Enter a 2-digit integer from 10 to 99>>");
}else{
System.out.println ("No! 10 and 1 are different");
System.out.print("Enter a 2-digit integer from 10 to 99>>");
}
}
}
}
scanner.close();
}
If an exception occurs once in the above code, instead of running a subsequent try block, just run the catch block
It runs normally when you run another code with a similar structure, but what's the problem?
I changed the part of Integer num = null; or num = scanner.nextInt(); to and fro.
The same problem continues to occur.
Oh, and how do we end the program by only pressing enter instead of zero in this question?
java while-loop try-catch
I'm also a beginner, but I'm leaving a reply.
catch(Exceptione){
System.out.print ("Invalid input". Please re-enter.>>");
scanner = new Scanner(System.in);
}
This problem can be solved by assigning scanner objects again in the exception processing part.
"How do I end a program by only pressing enter instead of zero?" -> Personally, I received a String scanner.nextLine() instead of scanner.nextInt(). After that, you can solve it through num.hasCode().
And personally, I wonder if there should be a final part.
I don't think there's anything that needs to be done here, and I think the program could die unexpectedly because there's finally. Also, if you solve the first question, you'll see that the output is unnatural. If there is no final part, I think we can print it out naturally.
잘못된 Please let me know if there is anything wrong!
581 PHP ssh2_scp_send fails to send files as intended
617 Uncaught (inpromise) Error on Electron: An object could not be cloned
571 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
910 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.