【问题标题】:How to prompt the user to only enter one of three options they can choose from and display an error message for wrong input如何提示用户只输入他们可以选择的三个选项之一,并显示错误输入的错误消息
【发布时间】:2019-10-23 03:41:57
【问题描述】:

此程序将提示用户输入介质(空气、水或钢)和距离。然后计算声波穿过介质的距离。

我编写了整个程序,但我没有阅读我的教授在作业中添加的最后一点,即下一段。现在我被卡住了,因为我不太确定如何将它添加到我的程序中。我使用的是 if 语句,但也许我可以将它添加到一个中?

程序提示输入介质:“输入以下选项之一:空气、水或钢:”并读取介质。如果介质不是空气、水或钢,程序将打印消息:“对不起,您必须输入空气、水或钢”,仅此而已。否则程序提示输入以下距离。

我尝试了一个while 循环并添加了另一个if 语句,但我的问题在于语法。因为我从来不需要命令用户输入特定的字符串。

public class SpeedOfSound {
    public static void main(String[] args) {

        double distance;
        double time;

        Scanner keyboard = new Scanner(System.in);
        //prompt the user to enter the medium through which sound will 
        System.out.print("Enter one of the following: air, water, or steel:");
        String input;
        input = keyboard.nextLine();

        // prompt the user to enter a distance

        System.out.print("Enter distance in feet: ");

        distance = keyboard.nextDouble();

        // determine if medium is air, water, steele and calculate

        if (input.equals("air")) {
            time = (distance / 1100);
            System.out.println("The total time traveled is " + time + " feet per second.");
        }
        else if (input.equals("water"))

        {
            time = (distance / 4900);
            System.out.println("The total time traveled is " + time + " feet per second.");
        }

        else if (input.equals("steel"))
        {
            time = (distance / 16400);
            System.out.println("The total time traveled is " + time + " feet per second.");
        }
    }
}

我的预期结果是让用户只输入 Air、water 或 Steel。

【问题讨论】:

  • 为了在错误选择后重复询问用户输入,您将需要一个 while 循环。
  • 您在使用 while 循环的正确轨道上。您需要存储用户输入,并根据可能的 HashSet -mySet.contains(userInput) 检查它 - 通过 while 循环的每次迭代以查看它是否是可接受的输入

标签: java loops if-statement


【解决方案1】:

您的代码有几个问题,我冒昧地纠正了它们。通读 cmets 以更好地理解代码的每个部分。

public class SpeedOfSound
{
    /* Best to declare it here so other methods have access to it. */
    private static final Scanner keyboard = new Scanner(System.in);
    /*
     * Declared as a class field so you can use it if you
     * have a need for it in addition to time calculated in main.
     */
    private static double distance;

    /**
     * Blocks program execution until a number has been detected as user input.
     * @return numeric representation of user input.
     */
    public static double getDistance()
    {
        System.out.println("Enter distance in feet: ");
        // CAREFUL: This will throw an exception if the user enters a String
        // return keyboard.nextDouble();
        while (keyboard.hasNext())
        {
            /*
             * Check if the user input is actually a number
             * and if it isn't print an error and get next token
             */
            String input = keyboard.nextLine();
            try {
                return Double.valueOf(input);
            }
            catch (NumberFormatException e) {
                System.out.println("Incorrect input, try again.");
            }
        }
        throw new IllegalStateException("Scanner doesn't have any more tokens.");
    }

    /**
     * Calculate the speed of sound for user input which is limited to:
     * <ul>
     *     <li>Air</li>
     *     <li>Water</li>
     *     <li>Steel</li>
     * </ul>
     * @return total time traveled in feet per second.
     */
    public static Double calculate()
    {
        Double time = null;

        //prompt the user to enter the medium through which sound will travel through
        System.out.println("Enter one of the following: air, water, or  steel:");

        // The loop will break the moment time is calculated
        while (time == null && keyboard.hasNext())
        {
            double distance;
            String input = keyboard.nextLine();

            //determine if medium is air, water, steele and calculate

            if (input.equals("air"))
            {
                distance = getDistance();
                time = (distance / 1100);
            }
            else if (input.equals("water"))
            {
                distance = getDistance();
                time = (distance / 4900);
            }
            else if (input.equals("steel"))
            {
                distance = getDistance();
                time = (distance / 16400);
            }
            else System.out.println("Incorrect input, try again.");
        }
        return time;
    }

    public static void main(String[ ] args)
    {
        Double time = calculate();
        System.out.println("The total time traveled is " + time + " feet per second.");
    }
}

然而,我处理这个任务的方法是在一个enum 中实现元素,并将大部分calculate() 方法移动到那里。这将允许您快速创建更多元素,例如 airwatersteel,而无需创建额外的 if 块来处理它们。

元素枚举器

public enum Element {

    AIR("air", 1100),
    WATER("water", 4900),
    STEEL("steel", 16400);

    private final String name;
    private final int factor;

    Element(String name, int factor) {
        this.name = name;
        this.factor = factor;
    }

    /**
     * @param element name of the element to calculate time for
     * @return total time traveled in feet per second for given element or
     *         {@code null} if no element matched the given name.
     */
    public static Double getTimeTraveledFor(String element)
    {
        /* Find an element that matches the given name */
        for (Element e : Element.values()) {
            /*
             * Validate the parameter without case consideration.
             * This might be a better way of validating input unless
             * for some reason you really want a case-sensitive input
             */
            if (e.name.equalsIgnoreCase(element)) {
                return SpeedOfSound.getDistance() / e.factor;
            }
        }
        return null;
    }
}

修改方法

public static Double calculate()
{
    Double time = null;

    //prompt the user to enter the medium through which sound will travel through
    System.out.println("Enter one of the following: air, water, or  steel:");

    // The loop will break the moment time is calculated
    while (time == null && keyboard.hasNext())
    {
        String input = keyboard.nextLine();
        time = Element.getTimeTraveledFor(input);
        if (time == null) {
            System.out.printf("%s is not a recognized element, try again.", input);
        }
    }
    return time;
}

【讨论】:

    【解决方案2】:
        while(true){  
         System.out.print("Enter distance in feet: ");
    
        String input;
                    input = keyboard.nextLine();
    
    
         //prompt the user to enter a distance
    
    
         System.out.print("Enter distance in feet: ");
    
         distance = keyboard.nextDouble();
    
         //determine if medium is air, water, steele and calculate
    
            if (input.equals("air"))
            {
    
    
            time = (distance / 1100);
    
            System.out.println("The total time traveled is " + time + " 
         feet per second.");
        break;
            }
    
            else if (input.equals("water"))
    
            {
            time = (distance / 4900);
    
            System.out.println("The total time traveled is " + time + " 
         feet per second.");
        break;
    
             }
    
    
    
             else if (input.equals("steel"))
    
             {
    
              time = (distance / 16400);
    
              System.out.println("The total time traveled is " + time + " 
         feet per second.");
        break;
    
    
              }
    else
     System.out.println("wrong choice");
    
    }
    

    【讨论】:

    • 如果您认为此答案可以改进,请考虑添加评论。
    • 我不是反对者;但我认为可以通过至少简要说明原始代码存在的问题、更改的内容以及(如有必要)如何缓解问题来改进这个答案。
    • 好的,谢谢,但这只是一个带有break语句的while循环,它是简单的解决方案
    • 只有当介质是正确的选项时,才会提示用户输入距离。
    • @MohammadSommakia 该解决方案有点复杂,因为它需要额外的验证。实现一个循环来不断询问输入只是解决方案的一部分。
    猜你喜欢
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多