Java validating Scanner Input with - java

How would I use InputMismatchException to determine if the value entered into the Scanner is not an integer? Basically, if they enter in a word instead of an integer I need to use InputMismatchException to return a message.
while (true) {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
try{
Integer.parseInt(i);
} catch (InputMismatchException e) {
System.out.println("Sorry, " + i + " is not a number.");
}
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}

Change your code as such:
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}
}
Changes:
Note use of nextLine(). This is because it seems you want to use the input as part of your error message, and nextInt() won't let you do that.
We can now move the i declaration inside the try block, along with
the code that uses it, so we won't issue "1 was not selected" when the input was "ssss" or whatever.
We use NumberFormatException, as that's what Integer.parseInt()
throws when it can't parse an integer from the String.

This is what i mean
while (true) {
Scanner sc = new Scanner(System.in);
int i = -1;
try
{
i = sc.nextInt();
}
catch (InputMismatchException e)
{System.out.println("Sorry, " + i + " is not a number.");}
if (i == 1)
System.out.println("1 was selected");
else
System.out.println("1 was not selected");
}

I am new to the programming, I think I got the code for your question.
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == parseInt(i, 3)) {
System.out.println(s+" is selected");
} else {
System.out.println("Input value is " + s);
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}}}
private static int parseInt(int i, int j) {
// TODO Auto-generated method stub
return 0;
}}
reference

Related

I need to terminate input sequence without entering any special value, just by pressing empty enter

Tried using hasNextInt() but it won't terminate unless an invalid input is entered.
Scanner sc= new Scanner(System.in);
int total=0; int temp;
while(sc.hasNextInt()) {
temp=sc.nextInt();
if(temp>0&&temp<17)total +=200;
else {
System.out.println("Invalid input"); break;
}
} System.out.println(total);
You could do something like this
Scanner sc = new Scanner(System.in);
String input = null;
do {
input = sc.nextLine();
try {
int temp = Integer.parseInt(input);
System.out.println("do your logic here, input was "+temp);
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("invalid input, terminating");
break;
}
} while (!"".equals(input));
System.out.println("--- end ---");
Or this
Scanner sc = new Scanner(System.in);
while (true) {
String input = sc.nextLine();
if ("".equals(input)) {
break;
}
try {
int temp = Integer.parseInt(input);
System.out.println("do your logic here, input was " + temp);
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("invalid input, terminating");
break;
}
}
System.out.println("--- end ---");

Java try-catch inside of a do-while loop

In my Java code shown below, I'm accepting user input of two doubles, and wrapping those values in a try-catch that handles an InputMismatchException. I've also wrapped a do-while loop around this try-catch block. I'm trying to craft the code in a way that handles the case where if a user inputs the wrong type for "number2", then the loop doesn't start over and ask the user to input "number1" all over again. I've been scratching my head on the best way to implement this and am open to any feedback or suggestions.
So the test case would be; the user inputs the right type for number1, but the wrong type for number2, in which case, how can I implement the code so that it only asks for re-entry of number2 instead of re-starting the entire loop. I've tried nested try-catch, nested do-whiles, etc. Any thoughts?
import java.util.InputMismatchException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
System.out.println("You've entered the numbers " + number1 + " " + number2);
continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
} while (continueInput);
}
}
You can extract method which takes Supplier
private <T> T executeWithRetry(String initialText, String retryText, Supplier<T> supplier) {
System.out.println(initialText);
while (true) {
try {
return supplier.get();
} catch (InputMismatchException ex) {
System.out.println(retryText);
}
};
}
And use it like
double number1 = executeWithRetry(
"Enter your first number: ",
"Try again, a double is required.",
() -> input.nextDouble()
)
Just split the process of reading the 2 values apart. This way you can individually check if an InputMismatchException occurs and handle it individually for each variable.
continueInput = false;
do {
try {
System.out.print("Enter your first number: ");
double number1 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);
continueInput = false;
do {
try {
System.out.print("Enter your second number: ");
double number2 = input.nextDouble();
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
continueInput = true;
}
} while (continueInput);
try this,
Scanner input = new Scanner(System.in);
boolean continueInput = true;
double number1 = 0;
while (continueInput) {
try {
System.out.print("Enter your first number: ");
number1 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
continueInput = true;
double number2 = 0;
while (continueInput) {
try {
System.out.print("Enter your second number: ");
number2 = input.nextDouble();
continueInput = false;
} catch (InputMismatchException ex) {
System.out.println("Try again, a double is required.");
input.nextLine();
}
}
System.out.println("You've entered the numbers " + number1 + " " + number2);

Stuck with detecting next line from console

I am banging my head to the wall but just can't figure out what is going wrong. Simple program but not working. I need to get 3 inputs(integers) from user. End the program on either array full or when user presses enter. Here is what i am trying without any luck. It works fine all the situtations EXCEPT it cant detect nextline.
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
if (sc.next().isEmpty() || sc.next().equals("\n")){
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
Please help me . Why is it not detecting next line. I have googled already and tried lot of solutions provided but none worked for me. Any HELP!!!
Thanks
Edited code :
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
while (true) {
System.out.println("Enter int");
if (sc.hasNextInt() && counter <= 2) {
intArray[counter] = sc.nextInt();
counter++;
} else {
if (counter >= 3) {
System.out.println("Array is full");
System.out.println("Array ELemnets : " + Arrays.toString(intArray));
break;
}
String next = sc.next();
if (next.isEmpty() || next.equals("\n"))
{
System.out.println("Its empty");
break;
} else {
System.out.println("wrong input.");
}
}
}
sc.close();
}
int[] intArray = new int[3];
int counter = 0;
boolean enterPressed = false; // added boolean to test if they entered a blank line
try (
Scanner sc = new Scanner(System.in); // declaring in a try-with-resources, so it automatically closes.
) {
System.out.println("Start!!");
System.out.println("Enter int"); // Have to print this the first time
while (counter < 3 && !enterPressed) {
if (counter > 0) { System.out.println("Enter int"); }
String next = sc.nextLine(); // just grab a line (the user pressed enter)
if (next.isEmpty()) {
enterPressed = true;
} else {
try {
intArray[counter] = Integer.parseInt(next);
counter++;
} catch (NumberFormatException ex) {
System.out.println("wrong input.");
}
}
}
}
Your code is sticking because it's waiting on the conditional check for sc.hasNextInt(). The solution I propose below, manually parses the user-input string to see if it's an int, rather than using the Scanner's functionality to check if it's an int or not.
I left some comments in the code to hopefully add clarity. Let me know if anything doesn't make sense, and I'm happy to elaborate!
import java.util.Arrays;
import java.util.Scanner;
public class ScannerTestNew {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] intArray = new int[3];
int counter = 0;
System.out.println("Start!!");
// Variable used to hold the user's input via the Scanner.
String userInput = null;
while (true) {
System.out.print("Enter an integer: ");
userInput = sc.nextLine();
// Check to see if an empty string/enter/return has been input:
if (userInput.length() == 0) {
System.out.println("Input is empty!");
break;
}
// Checking to see if the input can be parsed into an int. If it can't, retry.
int intInput = 0;
try {
intInput = Integer.parseInt(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input for type Integer. Please try again.");
continue;
}
// We know we have an int at this point. Checking that the array isn't already
// filled.
if (counter <= 2) {
intArray[counter] = intInput;
counter++;
// The array is filled, act accordingly.
} else if (counter > 2) {
System.out.println("Array is full.");
System.out.printf("Array Elements: %s", Arrays.toString(intArray));
break;
}
sc.close();
}
}
}

Make a loop AND catch using Strings instead of ints? (java)

I'm trying to make a text based rock paper scissors. I want the player to choose what they want to play to, for example "best (user response/2 + 1) out of (user response)" then it asks for verification if they would like to play to that number. If they say yes it continues the game with that score, if no it loops back up and lets them choose another number and I have an else that reminds them they can either select yes or no. When they are originally asked, letters don't effect and they are asked to try again. On the second loop around (when you say no) if you enter a String instead of an Int it crashes. Here what I have.
System.out.println("Best of:");
String line = userIn.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
bestOf = Integer.parseInt(line);
break;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = userIn.nextLine();
}
System.out.println("Okay, so you want to play best " + (bestOf / 2 + 1) + " of " + bestOf + "?");
String response2 = userIn.nextLine();
while (true) {
if (response2.contains("n")) {
System.out.println("What do you wish to play to then, " + name + "?");
bestOf = userIn.nextInt();
response2 = "y";
} else if (response2.contains("y") || response2.contains("Y")) {
winScore = (bestOf / 2 + 1);
System.out.println("Okay, best " + (bestOf / 2 + 1) + " of " + bestOf + " it is!");
break;
} else {
System.out.println("That's not a valid response! Try again.");
response2 = userIn.nextLine();
}
}
Instead of using parseInt use the string, in other words the input take it as string (even if is a number) them use the function "isNumber" too check if the string the user put is a number if not, do a while
System.out.println("Best of:");
String line = userIn.nextLine();
String aux = line;
do{
if (line.length() > 0)
aux = line;
if(!isNumeric(aux)){
System.out.println("Please enter a number");
line = userIn.nextLine();
}
}while(!isNumeric(aux));
bestOf = Integer.parseInt(aux);
so
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
You can extract your loop as a method and use it in second case as well.
private Integer readInt(Scanner scanner){
String line = scanner.nextLine();
while (true) {
if (line.length() > 0) {
try { //try catch to stop strings for a response
Integer result = Integer.parseInt(line);
return result;
} catch (NumberFormatException e) {
}
}
System.out.println("Please enter a number");
line = scanner.nextLine();
}
}
or even better:
private Integer readInt(Scanner scanner){
Integer result;
do{
try{
return scanner.nextInt();
} catch (InputMismatchException e){
scanner.nextLine();
System.out.println("Please enter a number");
}
} while (true);
}

How to check if user input is String, double or long in Java

I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}

Categories