显示菜单编译错误

时间:2014-09-22 22:38:55

标签: java menu compiler-errors

我只是对为什么会出现编译错误感到困惑,应该如何修复它。此外,在用户输入有效整数时失败的最后一个if语句中,我应该再次重复菜单。我该怎么办?提前谢谢。

 public class MainMenu {
 public static void main(String[] args)
    {
     System.out.println("My First Java program can do many things!");
     System.out.println("1.Estimate population\n2.Generate random integer\n3. Print ASCII      table\n4. Approximate pi by iteration");
     System.out.println("What would you like to do? (1-4)");
     System.out.print("Your choice: ");
     int input = 0;
     Scanner keyboard = new Scanner(System.in);
     switch (keyboard.nextInt())
     {
         case 1:
             System.out.println("You chose to estimate population.");
             break;
         case 2:
             System.out.println("You chose to generate random integer.");
             break;
         case 3:
             System.out.println("You chose to print ASCII table.");
             break;
         case 4:
             System.out.println("You chose to approximate pi by iteration.");
             break;
     }

     if(input>4 || input<1)
     {
         System.out.println("Sorry, I don't know what to do. Please try again.");   
         keyboard.next();
         if(!keyboard.hasNextInt()) 
    {
         System.out.println("Sorry, only integers allowed for this menu. Good-bye!");
         System.exit(0);
     }
  keyboard.next();
  input = keyboard.nextInt();
  keyboard.nextLine();
}

1 个答案:

答案 0 :(得分:0)

您的代码需要进行大量更改才能使其正常工作,首先您需要连续循环,这将持续运行并等待用户输入。如果输入不是整数,那么你必须捕获一个InputMismathexeption,你必须在代码的开头做。  提供代码是不错的主意,这会阻止你尝试不同的方式。我仍在附上代码。

import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
    System.out.println("My First Java program can do many things!");
System.out.println("1.Estimate population\n2.Generate random integer\n3. Print   ASCII      table\n4. Approximate pi by iteration");
    System.out.println("What would you like to do? (1-4)");
    System.out.print("Your choice: ");

    Scanner keyboard = new Scanner(System.in);
    while (true) {
        int input = 0;
        try {
            input = keyboard.nextInt();
        } catch (InputMismatchException e) {
            System.out
                    .println("Sorry, only integers allowed for this menu. Good-bye!");
            System.exit(0);
        }
        switch (input) {
        case 1:
            System.out.println("You chose to estimate population.");
            break;
        case 2:
            System.out.println("You chose to generate random integer.");
            break;
        case 3:
            System.out.println("You chose to print ASCII table.");
            break;
        case 4:
            System.out.println("You chose to approximate pi by iteration.");
            break;
        }

        if (input > 4 || input < 1) {
            System.out
                    .println("Sorry, I don't know what to do. Please try again.");
        }
    }
}
}