如何使菜单重新出现在java中

时间:2014-03-12 19:47:45

标签: java menu

import java.util.*;
public class LabTest1
{
public static void main(String[] args) 
    {
        Scanner console = new Scanner(System.in);
        double Choice1;
        double Choice2;
        int MenuChoice;
        System.out.print("Please enter the length: ");
        Choice1 = console.nextDouble();

        System.out.print("Please enter the width: ");
        Choice2 = console.nextDouble();

        System.out.println("=============================");
        System.out.println("|   MENU SELECTION          |");
        System.out.println("=============================");
        System.out.println("| Options:                  |");
        System.out.println("| 1. Calculate the area     |");
        System.out.println("| 2. Calculate the perimeter|");
        System.out.println("| 3. Exit                   |");
        System.out.println("=============================");
        MenuChoice = console.nextInt();
        System.out.print(" Select option: ");

    switch (MenuChoice)
    {
    case 1:
        System.out.println("Calculate the area selected");   
        System.out.println(Choice1 * Choice2);
        break;
    case 2:
      System.out.println(" Calculate the perimeter selected");  
      System.out.println(2*(Choice1 + Choice2));
      break;
    case 3:
        System.out.println("Exit selected");
        System.out.println(Choice1 + Choice2);
        break;

    default:
        System.out.println("Invalid selection");
        break; 
    }

    }
}

我需要这样做,如果值相等,它应该显示一条消息,表示值代表一个正方形,并允许用户重新输入值,直到输入适当的值(是的,我知道一个正方形是一个矩形)

1 个答案:

答案 0 :(得分:1)

使用以下模式询问输入,拒绝无效输入和循环:

boolean isValidInput = false;
[print prompt for input]
while (!isValidInput) {
   input = ...
   if (input is not valid) {
       print [invalid input, what is right form]
   } else {
       isValidInput = true;
   }
 }

顺便说一句,你应该使用尽可能少的文本。打印请求以及您正在执行的操作,以及每次输入错误信息时输入错误的提示。