I have a user input validate function:
public int UserChoiceValidate() {
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.print("Please enter your choice: ");
while (!sc.hasNextInt()) {
System.out.print("Input invalid, please retry: ");
sc.nextLine(); // consume left over
}
choice = sc.nextInt();
if (choice <= 0 || choice > 5) {
System.out.println("Choice not included, please retry");
}
} while (choice <= 0 || choice > 5);
return choice;
}
The code will repeat
Input invalid, please retry:Input invalid, please retry:Input invalid, please retry:
when I spam enter and then type in an invalid input.
How do I fix this error without having to rewrite it as reading a String instead of an int. I have quite a few functions with the same struction and would like to avoid having to rewrite them all.
I'm not certain what you mean by "rewrite it as a string validation", you are currently ignoring whatever input the user provides that isn't an int; if you want to treat "enter spam" special, you could do something like
System.out.print("Please enter your choice: ");
while (!sc.hasNextInt()) {
String line = sc.nextLine();
if (line.isEmpty()) {
continue;
}
System.out.print("Input invalid, please retry: ");
}
Related
I'm pretty new to programming. I need it to say "Enter the letter q to quit or any other key to continue: " at the end. If you enter q, it terminates. If you enter any other character, it prompts you to enter another positive integer.
import java.util.Scanner;
public class TimesTable {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("------------------------------------------------");
for(int i = 1 ;i<=tableSize;i++) {
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
Do this to have the user input a letter
Info:
System.exit(0) exits the program with no error code.
nextLine() waits for user to enter string and press enter.
nextInt() waits for user to enter int and press enter.
Hope this helps!
Scanner input = new Scanner(System.in);
String i = input.nextLine();
if(i.equalsIgnoreCase("q")) {
System.exit(0);
}else {
System.out.println("Enter a postive integer: ");
int i = input.nextInt();
//continue with your code here
}
This looks like homework ;-)
One way to solve this problem is to put your code that prints your messages and accepts your input inside a while loop, maybe something like:
Scanner input = new Scanner(System.in);
byte nextByte = 0x00;
while(nextByte != 'q')
{
System.out.println("Enter a postive integer: ");
int tableSize = input.nextInt();
printMultiplicationTable(tableSize);
System.out.println("Enter q to quit, or any other key to continue... ");
nextByte = input.nextByte();
}
use a do-while loop in your main method as below
do {
System.out.println("Enter a postive integer: ");
String tableSize = input.next();
if (!"q".equals(tableSize) )
printMultiplicationTable(Integer.parseInt(tableSize));
}while (!"q".equals(input.next()));
input.close();
you would also want to have a try-catch block to handle numberFormatException
I want to validate user input using the exception handling mechanism.
For example, let's say that I ask the user to enter integer input and they enter a character. In that case, I'd like to tell them that they entered the incorrect input, and in addition to that, I want them to prompt them to read in an integer again, and keep doing that until they enter an acceptable input.
I have seen some similar questions, but they do not take in the user's input again, they just print out that the input is incorrect.
Using do-while, I'd do something like this:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
do {
i = reader.nextInt();
} while ( ((Object) i).getClass().getName() != Integer ) {
System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);
PROBLEMS:
An InputMismatchException will be raised on the 5th line, before the statement checking the while condition is reached.
I do want to learn to do input validation using the exception handling idioms.
So when the user enters a wrong input, how do I (1) tell them that their input is incorrect and (2) read in their input again (and keep doing that until they enter a correct input), using the try-catch mechanism?
EDIT: #Italhouarne
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
In Java, it is best to use try/catch for only "exceptional" circumstances. I would use the Scanner class to detect if an int or some other invalid character is entered.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean gotInt = false;
while (!gotInt) {
System.out.print("Enter int: ");
if (scan.hasNextInt()){
gotInt = true;
}
else {
scan.next(); //clear current input
System.out.println("Not an integer");
}
}
int theInt = scan.nextInt();
}
}
Here you go :
Scanner sc = new Scanner(System.in);
boolean validInput = false;
int value;
do{
System.out.println("Please enter an integer");
try{
value = Integer.parseInt(sc.nextLine());
validInput = true;
}catch(IllegalArgumentException e){
System.out.println("Invalid value");
}
}while(!validInput);
You can try the following:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
The program that I have written below was designed so that if a user doesn't enter an integer when prompted, the program will loop until they do. This works for the initial check, but the second check does not work. The code is as follows:
import java.util.Scanner;
public class SafeInput
{
public static void main(String[]args)
{
System.out.println("Please enter any integer. If you want to exit, enter -1>");
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt())
{
String garbage = scan.nextLine();
System.out.println("You've entered garbage.");
}
int input = scan.nextInt();
while(input != -1)
{
System.out.println("\nYou entered: "+input);
System.out.println("Please enter any integer. If you want to exit, enter -1>");
while(!scan.hasNextInt())
{
System.out.println("You've entered garbage.");
String garbage1 = scan.nextLine();
}
input = scan.nextInt();
}
System.out.println("-1 entered. Goodbye");
}
}
Here's what happens when I execute the program:
Please enter any integer. If you want to exit, enter -1>
this is a string
You've entered garbage.
1
You entered: 1
Please enter any integer. If you want to exit, enter -1>
2
You entered: 2
Please enter any integer. If you want to exit, enter -1>
this is also a string
You've entered garbage.
You've entered garbage.
string
You've entered garbage.
1
You entered: 1
Please enter any integer. If you want to exit, enter -1>
2
You entered: 2
Please enter any integer. If you want to exit, enter -1>
-1
-1 entered. Goodbye
Why is it that when I fail the second check for an integer, the program outputs:
You've entered garbage.
You've entered garbage.
Instead of:
You've entered garbage.
Thanks!
second while loop should be updated like below.
while(input != -1)
{
System.out.println("\nYou entered: "+input);
System.out.println("Please enter any integer. If you want to exit, enter -1>");
scan.nextLine();
while(!scan.hasNextInt())
{
System.out.println("You've entered garbage");
String garbage1 = scan.nextLine();
}
input = scan.nextInt();
}
use next() instead of nextLine().
while(input != -1) {
System.out.println("\nYou entered: "+input);
System.out.println("Please enter any integer. If you want to exit, enter -1>");
while(!scan.hasNextInt())
{
System.out.println("You've entered garbage.");
String garbage1 = scan.next();
}
input = scan.nextInt();
}
Look at Scanner#nextLine() java doc,
This method returns the rest of the current line, excluding any line
separator at the end. The position is set to the beginning of the next
line.
See code
Debug:
while(input != -1)
{
System.out.println("\nYou entered: "+input);
System.out.println("Please enter any integer. If you want to exit, enter -1>");
while(!scan.hasNextInt())
{
System.out.println("-- Second -- ");
System.out.println("You've entered garbage.");
String garbage1 = scan.nextLine();
System.out.println(" garbage1 -> " + garbage1);
}
input = scan.nextInt();
}
Output:
Please enter any integer. If you want to exit, enter -1>
q
-- First --
You've entered garbage.
1
-- input --1
You entered: 1
Please enter any integer. If you want to exit, enter -1>
aa
-- Second --
You've entered garbage.
garbage1 ->
-- Second --
You've entered garbage.
garbage1 -> aa
ab
-- Second --
You've entered garbage.
garbage1 -> ab
Just for fun I did some 'enhanced' implementation. It should work correctly.
package example;
import java.util.Scanner;
public class SafeInput {
public static void main(String[] args) {
System.out.println("Please enter any integer. If you want to exit, enter -1>");
try (Scanner scan = new Scanner(System.in)) {
while (true) {
int input = 0;
String garbageOutput = null;
if (scan.hasNextInt() && ((input = scan.nextInt()) != -1)) {
System.out.println("\nYou entered: " + input);
System.out.println("Please enter any integer. If you want to exit, enter -1>");
} else if (scan.hasNextInt() && ((input = scan.nextInt()) == -1)) {
System.out.println("-1 entered. Goodbye");
break;
} else if (!scan.hasNextInt() && (scan.hasNextLine())
&& (!(garbageOutput = scan.nextLine()).isEmpty())) {
System.out.println(String.format("You've entered garbage - [%s]", garbageOutput));
}
}
}
}
}
If the allowed input in my program is only of type int but they user arbitrarily types in a not-allowed type character such as double or char etc. How do i handle that? I am sure there is so sort of Throw exception sort of thing but i am just not sure how it is done. Any suggestions will be appreciated
//here is my code
System.out.print("Too " +additionalInfo+ "! Try again: ");
attemptCounter++;
int x= input.nextInt(); // here is where i want the usr to type in their input
Use a loop to prompt user for input again after an invalid input e.g.
int userInput;
while(true) {
try {
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
userInput = input.nextInt();
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("Invalid Number, Please try again");
}
}
public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
if (number <=0) {
System.out.println(" please enter a valid number")
int number = input.nextInt();
}
input.close();
return number;
}
EDIT:
I should have used a while loop.. throwback to literally my first project.
System.out.print("Enter the number of cookies you'd like to make:");
int number = input.nextInt();
while(number<=0) //As long as number is zero or less, repeat prompting
{
System.out.println("Please enter a valid number:");
number = input.nextInt();
}
This is about data validation. It can be done with a do-while loop or a while loop. You can read up on topics of using loops.
Remarks on your codes:
You shouldn't declare number twice. That is doing int number more than once in your above codes (which is within same scope).
This way you have fewer superfluous print statements and you don't need to declare you variable multiple times.
public int inputNumber() {
Scanner input = new Scanner (System.in);
int number = 0;
do {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
} while(number <= 0);
input.close();
return number;
}
Couple of issues:
You are missing semicolon in you println method.
You are redefining the number within if
you are using if which is for checking number instead use while so until and unless user enters correct number you dont proceed.
public int inputNumber() {
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of cookies you'd like to make ");
int number = input.nextInt();
while (number <=0) {
System.out.println(" please enter a valid number");
number = input.nextInt();
}
input.close();
return number;
}
The classical way of doing that is to limit the number of retry and abort beyond that ::
static final int MAX_RETRY = 5; // what you want
...
int max_retry = MAX_RETRY;
int number;
while (--max_retry >= 0) {
System.out.print("Enter the number of cookies you'd like to make ");
number = input.nextInt();
if (number > 0) {
break;
}
System.out.println("Please enter a valid number")
}
if (max_retry == 0) {
// abort
throw new Exception("Invalid input");
}
// proceed with number ...