如果输入无效选项,如何循环回多个选项?

时间:2014-07-07 02:21:30

标签: java

我有一个程序,它有几个以不同方式操作给定字符串的方法。我需要为用户提供一个菜单来选择要执行的方法。如果输入了无效选项,则需要提供菜单并允许用户再次尝试。在运行方法之后,还需要为用户提供选择其他选项或结束程序的选项。我编写选项并运行不同的方法没有问题,但我不确定如何再次运行它。以下是我在测试课上的工作。

import java.util.Scanner;


public class TestStringManip {
        //=================MAIN===============
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = in.nextLine();

        StringManipulation newString = new StringManipulation(input);

        String menu = newString.getMenu();
        System.out.println(menu);
        int option = in.nextInt();

        if (option == 1)
        {
            String upperCase = newString.getUpperCase(input);
            System.out.println(upperCase);
        }

        else
        {
            System.out.println("Error: must select options 1-5 from menu");
            System.out.println(menu);
            int option2 = in.nextInt();
        }

    }

}

我尝试过一些新东西。这就是我现在所拥有的。现在它将再次打印菜单,但是当我选择一个新选项时,它不会调用该方法。

import java.util.Scanner;


public class TestStringManip {
        //=================MAIN===============
    public static void main(String[] args) 
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = in.nextLine();

        StringManipulation newString = new StringManipulation(input);

        String menu = "\n Please select an option to perform"
                + "\n1 (1) Get all uppercase letters."
                + "\n2 (2) Get every second letter."
                + "\n3 (3) Replace vowels with _ "
                + "\n4 (4) Get a count of all vowels."
                + "\n5 (5) Get position of all vowels.";
        System.out.println(menu);
        int option = in.nextInt();


        do
        {
            if (option == 1)
            {
                newString.getUpperCase(input);
            }

            else if (option == 2)
            {
                newString.getEverySecond(input);
            }

            else
            {
                System.out.println("Error must select 1-5");
                System.out.println(menu);
                option = in.nextInt();
            }
        }while (option < 1 || option > 5);
    }

}

1 个答案:

答案 0 :(得分:0)

do { // do ... while loop
    if (option == 1)
            {
                String upperCase = newString.getUpperCase(input);
                System.out.println(upperCase);
            }

            else
            {
                System.out.println("Error: must select options 1-5 from menu");
                System.out.println(menu);
                option = in.nextInt();
            }    
}   while (option < 1 || option > 5); // keep looping as long as it is less than 1 or more than 5

使用do ... while循环检查选项是否在1 - 5之间,请注意我删除了option2变量并使用/ check on变量“option”而不是