在公共方法中运行 Java 哨兵控制的 do-while 循环

时间:2021-05-18 18:04:20

标签: java java.util.scanner do-while sentinel

我有一个方法 public static int payMethod,参数 input 用于 Scanner 来获取输入。显然,我可以完全删除该方法并将所有内容放入 main 方法中,但我正在尝试学习使用不同类型的方法,因此这不是一个真正的选择。

我的目标是让用户输入 1、2 或 3。如果他们输入其他内容,则程序会再次询问,直到用户输入 1、2 或 3。

import java.util.*;
public class test {
    public static void main(String [] args) {
        Scanner input = new Scanner(System.in);

        //User input on selection
        System.out.println("Choose 1, 2, or 3.");
        double choice;

        //Repeat until payment selection is valid choice
        choice = choiceMethod(input);

        input.close(); //Close Scanner
    }

    public static int choiceMethod (Scanner input) {
        do {
            System.out.print("Which choice would you like? ");
            if (input.nextDouble() < 1 || input.nextDouble() > 3 || input.nextDouble() != (int)input.nextDouble()) {
                System.out.println("This is not a valid option. Please choose either option 1, 2, or 3.");
            }
        } while (input.nextDouble() < 1 || input.nextDouble() > 3 || input.nextDouble() != (int)input.nextDouble());
        return (int)input.nextDouble();
    }
}

这是我不稳定的输入/输出。

Choose 1, 2, or 3.
Which choice would you like? 1

2
3
4
This is not a valid option. Please choose either option 1, 2, or 3.
5





1
1
2
Which choice would you like? 
2
3
4
5
This is not a valid option. Please choose either option 1, 2, or 3.

我试过更改参数无济于事,所以我确定问题出在方法中。感谢您的帮助,TIA。

0 个答案:

没有答案
相关问题