Как предложить пользователю ввести только один из трех вариантов, которые он может выбрать, и отобразить сообщение об ошибке при неправильном вводе - PullRequest
0 голосов
/ 07 июня 2019

Эта программа предложит пользователю ввести среду (воздух, вода или сталь) и расстояние. Затем рассчитайте расстояние, которое звуковая волна пройдет через среду.

Я написал всю программу, но не прочитал последнюю часть, которую мой профессор добавил к домашней задаче, а именно к следующему абзацу. Теперь я застрял, потому что я не совсем уверен, как добавить это в мою программу. Я использовал оператор 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.");
        }
    }
}

Мой ожидаемый результат - заставить пользователя печатать только воздух, воду или сталь.

Ответы [ 2 ]

1 голос
/ 07 июня 2019

Было несколько проблем с вашим кодом, и я позволил себе исправить их. Прочитайте комментарии, чтобы лучше понять каждую часть кода.

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(). Это позволит вам быстро создавать больше элементов, таких как air, water и steel, не создавая дополнительных блоков 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;
}
0 голосов
/ 07 июня 2019
    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");

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...