您可以尝试的另一件事是,您可以继续要求用户输入正确的输入,而不是退出程序,只有在输入正确的输入后才继续操作。我不知道您的要求是什么,但是如果您想通过良好的代码习惯进行操作,则不应仅因为用户输入了错误的输入而终止程序。想象一下,如果您用错字搜索了一个单词,而Google刚刚关闭。
反正这就是我的做法
import java.util.Scanner;public class oddoreven { public static void main(String[] args) { int num; int x = 1; while (x == 1) { System.out.println("Enter a number to check whether or not it is odd or even"); Scanner s = new Scanner(System.in); boolean isInt = s.hasNextInt(); // Check if input is int while (isInt == false) { // If it is not int s.nextLine(); // Discarding the line with wrong input System.out.print("Please Enter correct input: "); // Asking user again isInt = s.hasNextInt(); // If this is true it exits the loop otherwise it loops again } num = s.nextInt(); // If it is int. It reads the input if (num % 2 == 0) System.out.println("The number is even"); else System.out.println("The number is odd"); // trying to figure out how to get the pre to terminate if you put in a value // that isn't a number System.out.println("Type 1 to continue, 0 to terminate"); x = s.nextInt(); } }}


