Строки как значения часового в цикле while - PullRequest
0 голосов
/ 29 сентября 2019

Я пытаюсь написать программу, которая спрашивает пользователя, хотят ли они ввести действительное число.Если да, то предложите пользователю ввести номер.Продолжайте запрашивать ввод цифр, пока пользователь не скажет «нет».Как только это произойдет, выведите среднее число введенных чисел.

Я думаю, что застрял, пытаясь реализовать строку для значения часового.Я хочу, чтобы значение дозорного было "нет".Но с этой последней попыткой, которую я имею здесь, при вводе «да» я получаю исключение InputMismatchException.Кроме того, не уверен, если это работа для дел / время или просто время.Что-то новое для всего этого и не знаю, как это сделать, поскольку у нас нет примеров использования строк для часовых.

public static void main(String[] args) {

int count = 0;
float total = 0;        
float inputNumber;


Scanner scan = new Scanner ( System.in );

System.out.println("Want to enter a number?");

String reply = "";


inputNumber = scan.nextFloat();

do {
    reply = scan.nextLine();
    if (reply.equalsIgnoreCase("yes")) {
        System.out.println("Enter a number > ");

        total+= inputNumber ;
        count++ ;

        System.out.println("Enter another number, or " +
                "enter \"no\" to terminate > " );
        inputNumber = scan.nextFloat(); 
    }
}   
while (! reply.equalsIgnoreCase("no")) ;

if (count != 0) {
    System.out.println("The average of the numbers is " + 
            (total / count));
}

}

}

1 Ответ

0 голосов
/ 29 сентября 2019
  • Удалить первый inputNumber = scan.nextFloat();
  • Исправить цикл.
  • Добавить scan.nextLine() после scan.nextFloat()
    public static void main(String[] args) {
        int count = 0;
        float total = 0f;
        float inputNumber = 0f;

        Scanner scan = new Scanner ( System.in );

        System.out.println("Want to enter a number?");
        String reply = scan.nextLine();

        while (reply.equalsIgnoreCase("yes")) {
            System.out.println("Enter a number > ");
            inputNumber = scan.nextFloat();
            scan.nextLine();
            total += inputNumber;
            count++;

            System.out.println("Enter another number, or enter \"no\" to terminate > ");
            reply = scan.nextLine();
        }

        if (count != 0) {
            System.out.println("The average of the numbers is " + (total / count));
        }
    }

РЕДАКТИРОВАТЬ

    public static void main(String[] args) {
        int count = 0;
        float total = 0f;
        float inputNumber = 0f;

        Scanner scan = new Scanner ( System.in );

        System.out.println("Want to enter a number?");
        String reply = scan.nextLine();

        if (!reply.equalsIgnoreCase("yes"))
            return;

        System.out.println("Enter a number > ");
        while (!reply.equalsIgnoreCase("no")) {
            reply = scan.nextLine();
            try {
                inputNumber = Float.parseFloat(reply);
            } catch (NumberFormatException e) {
                continue;
            }
            total += inputNumber;
            count++;
            System.out.println("Enter another number, or enter \"no\" to terminate > ");
        }
        if (count != 0) {
            System.out.println("The average of the numbers is " + (total / count));
        }
    }
...