Ввод необходимо вводить дважды, и нельзя вводить строки при их вводе. - PullRequest
0 голосов
/ 12 ноября 2018

Мой код

package morrisJCh5Sec2;

import java.util.Scanner;

public class Ch5Sec2 {
    public static int collectInteger(String purpose, int minimum, int maximum) {

        Scanner input = new Scanner(System.in);
        System.out.println(purpose);
        System.out.printf("\tEnter an integer between " + minimum + " and " + maximum + ": ");
        int value = input.nextInt();
        while(input.hasNext()) {

            if(!input.hasNextInt()) {
                System.out.println("The value you enter needs to be between " + minimum + " and " + maximum + ". Please try again.");
                System.out.printf("\tEnter an integer between " + minimum + " and " + maximum + ": ");
                value = input.nextInt();
                input.next();
                continue;
                //not an integer
            }//end not int if
            else {
                value = input.nextInt();
                if(value >= minimum && value <= maximum) {
                    return value;
                }
                else {
                    System.out.println("The value you enter needs to be between " + minimum + " and " + maximum + ". Please try again.");
                    System.out.printf("\tEnter an integer between " + minimum + " and " + maximum + ": ");
                    value = input.nextInt();
                }//end else out of bounds

            }
            //input.close();
        }

        return 0;
    }//end collectInteger
    public static void main(String args[]) {
        final int LOW_INT = 0;
        final int HIGH_INT = 100;
        int inputValue = collectInteger("Enter the number of cats.", LOW_INT, HIGH_INT);
        System.out.printf("Your number of cats was %d.\n", inputValue);
    }//end main
}//end class

Мой вывод:

Enter the number of cats.
    Enter an integer between 0 and 100: -56
-56
The value you enter needs to be between 0 and 100. Please try again.
    Enter an integer between 0 and 100: 101
101
The value you enter needs to be between 0 and 100. Please try again.
    Enter an integer between 0 and 100: jads
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at morrisJCh5Sec2.Ch5Sec2.collectInteger(Ch5Sec2.java:30)
    at morrisJCh5Sec2.Ch5Sec2.main(Ch5Sec2.java:42) 

Мой вывод должен позволять вводить строку и снова запрашивать целое число.Другая проблема заключается в том, что мой код не должен вводить пользователя дважды при вводе, он должен просто принять пользовательский ввод один раз и запустить код.

1 Ответ

0 голосов
/ 12 ноября 2018

У вас есть много дополнительных звонков на next() и nextInt() в вашем коде. Вы можете преобразовать свой код в цикл do-while. Также у вас есть дополнительный звонок на next() в первом if. Затем в вашем внутреннем else вы запрашиваете пользовательский ввод для nextInt(), но так как вы вызываете nextInt() в начале цикла, это дополнительный, поэтому он запрашивает ввод дважды. Также в вашем первом if он обрабатывает, если ввод не является синтаксическим анализом int. Если это не так, у вас есть value = input.nextInt(), что приведет к исключению несоответствия ввода. Вместо этого вызовите пробел next(), чтобы очистить неправильный ввод:

public static int collectInteger(String purpose, int minimum, int maximum) {

        Scanner input = new Scanner(System.in);
        System.out.println(purpose);
        System.out.printf("\tEnter an integer between " + minimum + " and " + maximum + ": ");
        int value;
        do {    
            if(!input.hasNextInt()) {
                System.out.println("The value you enter needs to be between " + minimum + " and " + maximum + ". Please try again.");
                System.out.printf("\tEnter an integer between " + minimum + " and " + maximum + ": ");
                input.next();    //clear bad input                                                     
            }
            else {
                value = input.nextInt();
                if(value >= minimum && value <= maximum) {
                    return value;
                }
                else {
                    System.out.println("The value you enter needs to be between " + minimum + " and " + maximum + ". Please try again.");
                    System.out.printf("\tEnter an integer between " + minimum + " and " + maximum + ": ");

                }

            }

        } while(input.hasNext());
        return 0;
}

Пример вывода:

Enter the number of cats.
Enter an integer between 0 and 100: -51
The value you enter needs to be between 0 and 100. Please try again.
    Enter an integer between 0 and 100: 20000
The value you enter needs to be between 0 and 100. Please try again.
    Enter an integer between 0 and 100: Hello
The value you enter needs to be between 0 and 100. Please try again.
    Enter an integer between 0 and 100: 4
Your number of cats was 4.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...