reprompting for a string?
Can someone explain to me how to have a user input information again if their initial one was incorrect? For example, in this it will have the user go back to select an invoice number within range, but how do you do so if they enter words? I've tried next() and nextLine() but it hasn't worked. Thanks for any tips.
Scanner input = new Scanner(System.in);
System.out.println("What is the invoice number for your purchase?");
invoice = input.nextInt();
System.out.println("What is the sale amount of your purchase?");
amount = input.nextDouble();
while (invoice < 1000 || invoice > 8000)
System.out.println("You have entered an invalid invoice number.");
System.out.println("Please select a number between 1000 and 8000.");
invoice = input.nextInt();//having trouble knowing how to input this if it were a string.
Re: reprompting for a string?
Give us examples of a correct and incorrect responses.
Why use a string when the input is a number?
Usually, when a String is used for input, only very few responses are expected. For example, an item from a menu to select which action the program should take next, or a Yes/No answer to choose whether the program should run again. With just a few inputs, a branching statement using an if or switch can be used, and if none of the branches is chosen due to incorrect input, the user is given an error message and asked again for correct input.
The example you've shown which requires the input to be in a correct numerical range could accept a String input but then the input would be converted to a number (probably an int) to determine if it falls within the correct range:
int inputValue = Integer.parseInt( inputString );
Then inputValue can be used to determine if the input was correct.