如何使用循环验证选择菜单

时间:2016-04-28 11:21:21

标签: java validation loops

有人可以编辑我的代码,使其循环选择菜单。如果选择不是5个选项之一,它将提示用户重新输入,直到它是有效选项。如果可能的话,解释也会有所帮助。感谢

这是我的代码。

import java.util.*;
public class ShapeLoopValidation
{
    public static void main (String [] args)
    {
        chooseShape();
    }

    public static void chooseShape()
    {
        while (true){
            Scanner sc = new Scanner(System.in);
            System.out.println("Select a shape number to calculate area of that shape!");
            System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
            int shapeChoice = sc.nextInt();
            //while (true) {
            if (shapeChoice >= 1 && shapeChoice <=4)
            {
                if (shapeChoice == 1)
                {
                    circle();
                }
                else if (shapeChoice == 2)
                {
                    rectangle();
                }
                else if (shapeChoice == 3)
                {
                    triangle();
                }
                else if (shapeChoice == 4)
                {
                    return;
                }
            }
            else
            {
                System.out.print("Error : Choice " + shapeChoice + "Does not exist.");
            }
        }

        class Test {
            int a, b;

            Test(int a, int b) {
                this.a = a;
                this.b = b;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

首先:看看switch

第二:阅读一下do-while loops(它们通常非常适合这种情况)。

现在,我将如何实现它(但你应该学习如何在这种情况下进行循环):

public static void chooseShape () {

    boolean valid = false;
    do {
        Scanner sc = new Scanner(System.in);
        System.out.println("Select a shape number to calculate area of that shape!");
        System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
        int shapeChoice = sc.nextInt();

        switch (shapeChoice) {
            valid = true;
            case 1:
                circle();
                break;
            case 2:
                rectangle();
                break;
            case 3:
                triangle();
                break;
            case 4:
                return;
            default:
                valid = false;
                System.out.println("Error : Choice " + shapeChoice + "Does not exist.");
                System.out.println("Please select one that exists.") 
        }
    } while (!valid)
}

答案 1 :(得分:0)

使用do-while流量控制直到输入EXIT代码:

int shapeChoice;
do {
   System.out.println("Select a shape number to calculate area of that shape!");
   System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
   int shapeChoice = sc.nextInt();
   // then use if-else or switch   
} while (shapeChoice != 4);

使用break语句循环中断代码:

else if (shapeChoice == 4)
{
   break;
}