java - 如何不断要求用户选择有效选项?

标签 java

因此,用户必须在 1 到 3 之间选择一个数字。否则,他们会被告知重试。如果用户尝试一个小于 1 或大于 3 的数字,他们选择的任何数字都会存储在“选择”变量中,并导致程序在应该停止时继续运行。我以为会有一个简单的解决方案,但显然这超出了我作为初学者的范围。对我来说显而易见的事情是以某种方式清除或清空在用户输入不成功后分配给“选择”的值。这可能吗?

import java.util.Scanner;

public class Furniture2Test  {

    public static void main(String[] args) {

        wood();

    } // end main

    public static void wood() {

        int choice;

        int pine = 1;
        int oak = 2;
        int mahogany = 3;

        int pineCost = 100;
        int oakCost = 225;
        int mahoganyCost = 310;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("What type of table would you like?");
        System.out.println("1. pine");
        System.out.println("2. oak");
        System.out.println("3. mahogany");

        choice = keyboard.nextInt();

        if (choice == 1) {
            choice = pineCost;
        } else if (choice == 2) {
            choice = oakCost;
        } else if (choice == 3) {
            choice = mahoganyCost;
        } else if (choice > 3 || choice < 1) {
            System.out.println("Try again.");
            choice = -1;
            wood();
        }

        System.out.println("That will be $" + choice + ".");

        size(choice);

    } // end wood

    public static void size(int choice) {

        int sizeChoice;
        int large = 35;

        Scanner keyboard = new Scanner(System.in);

        System.out.println("What size will that be?");
        System.out.println("1. large");
        System.out.println("2. small");

        sizeChoice = keyboard.nextInt();

        if (sizeChoice == 1)
            System.out.println("That will be $" + (choice + large) + ".");
        else if (sizeChoice == 2)
            System.out.println("That will be $" + choice);
        else
            System.out.println("Please, enter either a 1 or a 2.");

    } // end size

}

最佳答案

您的要求可以通过 do...while 循环轻松完成。示例代码如下:

do{
    System.out.println("Choose option between 1 and 3");
    choice = keyboard.nextInt();
}while(!(choice > 3 || choice < 1));

if (choice == 1) {
    choice = pineCost;
} else if (choice == 2) {
    choice = oakCost;
} else if (choice == 3) {
    choice = mahoganyCost;
}

希望这对您有所帮助。

关于java - 如何不断要求用户选择有效选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19016090/

相关文章:

AWS EC2 上的 Java Web 服务 SSL?

java - 如何在Spring Boot中的@AfterThrowing方法中访问对象

java - 需要从 JFrame 中的单选按钮获取输入,并在另一个类中使用选定的输入

java - 有没有办法通过Java中的反射获取InnerClasses列表?

java - 升级 CXF 和 WSS4J 但找不到依赖项

java - RAML 是否支持同一内容类型的多个响应模式?

java - 创建 XML 的 Java 类有效,但在嵌入到 Android 应用程序时出现异常

java - 在 libgdx 中拉伸(stretch)/压缩图像

java - Androids Canvas.drawPath 是否使用 Canvas 中的裁剪集?

java - Canvas 的面积有多少