I'm a beginner with Java and I have the following code:
public class test
{
public static void main(String[] args)
{
int a ;
String b;
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter a: ");
a = input.nextInt();
} catch(Exception e )
{
System.out.println("That is not a number!");
}
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);
}
}
when I give a string instead of int the code performs further and I receive this result:
"Enter a:
fsd
That is not a number!
Enter your name:
Hello fsd"
How can I make an interruption after the catch? (I have already try with a new Scanner after catch, but I think there are also another ways)
Thanks in advance!
LE: I have managed to do that with the "input.next();". I actually wanted to tip in another value for the string b, but the program takes automatically the int a instead of a new value and prints "Hello vsd", although vsd was the input for a.
As stated by the documentation, the Scanner will not advance to the next token if the current token does not match an integer's format. Therefore, if an exception is not thrown, the token in not consumed, and you just get it the next time you call a nextXYZ method.
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
Instead of throwing and catching the exception (which is a heavy operation), you could use hasNextInt() to check it in advance:
int a ;
String b;
Scanner input = new Scanner(System.in);
System.out.println("Enter a: ");
if (input.hasNextInt()) {
a = input.nextInt();
} else {
System.out.println("That is not a number!");
// Skip the token so you won't get it later:
input.nextLine();
}
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);
Try this
public class Test{
public static void main(String[] args){
int a ;
String b;
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter a: ");
a = input.nextInt();
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);
}
catch(Exception e ){
System.out.println("That is not a number!");
}
}
}
Just modify your catch block as follow:
catch(Exception e )
{
System.out.println("That is not a number!");
System.exit(0);
}
You should try to use the following block
input.hasNextInt()
instead as it doesn't require you to use a catch or throw exception, but rather if and else statements.
Your code still carries on because the catch block simply catches the exception and replaces it with a System.out.println that prints "That is not a number!"
} catch(Exception e )
{
System.out.println("That is not a number!");
}
Upon doing so the code continues to
System.out.println("Enter your name: ");
b = input.next();
System.out.println("Hello " + b);
Related
I am trying to prompt a user with the value they inputted and an error message if it's not an integer. When I try to prompt them, their input stays 0 when the input is a double or string.
//main method
public static void main(String[] args) {
int i = 0;
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
try {
inputNum = Integer.parseInt(input.next());
System.out.println("Value entered is " +
String.valueOf(inputNum));
} catch(NumberFormatException e) {
System.out.println("Value entered is " +
String.valueOf(inputNum));
System.out.println(String.valueOf(inputNum) + " is not an integer.");
}
}
}
If the input is a double or a string then parseInt would throw an exception and inputNum would not be assigned any new value. You could store input.next() in a string before passing it to parseInt - or you might be able to use e in the catch block to figure out the bad value
String s;
//parse imput, display value
//and prompt user that their input is not a int
try {
s = input.next();
System.out.println("Value entered is " + s);
inputNum = Integer.parseInt(s);
} catch(NumberFormatException e) {
System.out.println(s + " is not an integer.");
}
}
}
Well, it's a concept ('ask user for some input, keep asking if it is not valid') that you may want to do more than once, so it has no business being in main.
Give it its own method.
This method would take as input a 'prompt' and will return a number. The purpose is to ask the user (with that prompt) for a number, and to keep asking until they enter one.
You can use while() to loop code until a certain condition is met, or simply forever, using return to escape the loop and the entire 'ask the user for a number' method in one fell swoop.
I've modified the code to make it work according to your need:
public static void main(String[] args) {
//instantiate new Scanner for user input
Scanner input = new Scanner(System.in);
//parse imput, display value
//and prompt user that their input is not a int
String inputNum = input.next();
try {
System.out.println("Value entered is " +
Integer.parseInt(inputNum));
} catch (NumberFormatException e) {
System.out.println("Value entered is " +
inputNum);
System.out.println(inputNum + " is not an integer.");
}
}
Above is the standard approach to check if a String is an integer in java. If you want a simpler & powerful way you can leverage the Apache Commons library:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final String num = input.next();
// check to see if num is a number
if (NumberUtils.isCreatable(num)) {
System.out.println("Value entered is " + num);
} else {
System.out.println("Value entered is " + num);
System.out.println(num + " is not a number.");
}
}
Note that NumberUtils#isCreatable checks for a wide variety of number formats(integer, float, scientific...)
If you want something equivalent to Integer#parseInt, Long#parseLong, Float#parseFloat or Double#parseDouble. Use instead, NumberUtils#isParsable.
There is an another concise way to do it without throwing any exception, you can use hasNextInt() to pre-validate if the input value is a valid integer before hand, then use nextInt() to read an integer without parsing the string:
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int inputNum;
if(scanner.hasNextInt()){
inputNum = scanner.nextInt();
System.out.println("Value entered is " + inputNum);
}else{
System.out.println(scanner.next() + " is not an integer.");
}
}
For a college assessment I'm having to use a Scanner called sc with a class-level scope, and the entirety of the program has to be contained in a single class. The main method calls a menu() method, which uses the Scanner and a for loop to call one of two methods in response to user input.
One of the two methods uses the Scanner to calculate the factorial of an input integer. Once the method is executed, the for loop in menu() continues. To avoid an InputMismatchException due to the user entering a float, I used try/catch. However when the program returns back to the menu() for loop the Scanner causes an InputMismatchException when assigning to choice. How can I get Scanner to prompt the user for input again? Apologies if I'm missing something obvious, this is the first programming language I've ever learned. This should be the stripped down compilable code:
package summativeassessment;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SummativeAssessment {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
menu();
}
public static void menu(){
String fName;
String sName;
System.out.print("Enter your first name: ");
fName = sc.next();
System.out.print("Enter your last name: ");
sName = sc.next();
try{
for(int choice = 1; choice!=0;){
System.out.print("Option 1 to generate username. Option 2 to calculate factorial. Press 0 to quit: ");
choice = sc.nextInt();
switch(choice){
case 2:
System.out.println(fName+" "+sName+", you have selected option 2");
numberFactorial();
break;
case 0:
break;
default:
System.out.println("Invalid option. Please try again.");
}
}
} catch(InputMismatchException ex){
String msg = ex.getMessage();
System.out.println(msg);
}
}
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
}
}
}
I debugged your code and got this result:
If you enter a float as input you trigger the InputMismatchException but there is still something in your buffer. So the next time sc.nextInt() is called, it won't wait until you input a value because something is in the buffer already, so it takes the next value out of the buffer and tries to interpret is as an integer. However, it fails to do so, because it is not an integer, so an InputMismatchException is raised again and caught in your menu's catch, now leading to the exit of the program.
The solution is to draw whatever is left in the buffer after the exception was raised the first time.
So the working code will contain a buffer clearing sc.next() inside the exception:
public static void numberFactorial(){
System.out.print("Enter a number: ");
try{
int numIn = sc.nextInt();
long result = numIn;
if(numIn>0){
for(int factor = 1; factor<numIn; factor++){
result *= factor;
if(factor==numIn-1){
System.out.println("The factorial is "+result);
}
}
}
else{
System.out.println("Enter a positive integer greater than 0");
}
}
catch(InputMismatchException ex){
System.out.println("Input invalid");
sc.next();
}
}
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);
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);
I looked through a bunch of other questions and online, but I can't find anything that answers this specifically. I'm trying to handle dealing with and determining valid input based on a Windows command line argument. As a sample, I was just seeing if an entered number was positive to be as easy as possible. The biggest issue, and what made me unable to find a specific answer, was I'm really trying to use recursion to make it keep asking until a valid input is entered, rather than just killing the program.
Algorithm:
If there is an argument provided and it's a positive integer
Display value
Otherwise
Until the argument is a positive number
Prompt for a positive integer
Display value
I wrestled with the code and eventually got this to work, but it seems really inefficient, repetitive and hacked together. At first, I had the while-loop inside the caught exceptions, but this allowed other things to slip through from the command line. How can I make this as efficient as possible and also prevent any logic errors or exceptions? What approach should I take with my algorithm when tackling this? Here's my code:
import java.util.Scanner;
public class Test
{
public static void main( String[] args )
{
String arg;
Scanner user_input = new Scanner(System.in);
int i = 0;
try {
arg = args[0];
i = Integer.parseInt(arg);
} catch( ArrayIndexOutOfBoundsException e ) {
arg = "";
} catch( NumberFormatException e2 ) {
arg = "";
}
while( i <= 0 )
{
System.out.print("Please type in a positive whole number. ");
arg = user_input.next();
try {
i = Integer.parseInt(arg);
} catch( NumberFormatException e2 ) {
System.out.print("That's a letter! ");
continue;
}
if( i <= 0 )
{
System.out.print("That's a negative. ");
}
}
System.out.println("Input is " + i);
}
}
Try this:
The code is quite lengthy this is because two separate try blocks are required; one for the command-line argument & the other for the argument provided via the scanner...
I had to create my own custom exception, "NegativeNumberException"...
import java.util.Scanner;
public class NegativeNumberException extends Exception{
NegativeNumberException(){
System.out.println(exceptionMessage);
}
String exceptionMessage = "Number must be positive";
static int num;
public static void main(String[] args) throws NegativeNumberException{
try
{
if(Integer.parseInt(args[0])<0){
throw new NegativeNumberException();
}
else{
int num = Integer.parseInt(args[0]);
System.out.println("Your number is: " + num);
}
}
catch(NumberFormatException ex){
System.out.println("That's not even a number.");
}
catch(NegativeNumberException ex){
ex.getMessage();
}
while(num==0){
try{
System.out.println("Enter a positive number:");
Scanner input = new Scanner(System.in);
int num1 = input.nextInt();
if(num1<0){
throw new NegativeNumberException();
}
num = num1;
break;
}catch(Exception ex){
System.out.println("Positive number only, try again...");
}
}//End While
System.out.println("Your number is:" + num);
}
}
Input: (Command-line): lol
Output
(Console):That's not even a number
Enter a positive int
(Console input via Scanner): -4
(Console):Number must be positive
Positive number only, try again...
Enter a positive number:
(Console input via Scanner): 3
(Console):Your number is: 3
I modified your code so that it runs the way you want. Try using this:
public static void main( String[] args ) {
String arg;
Scanner user_input = new Scanner(System.in);
int numTries = 0, value = 0;
try {
numTries = Integer.parseInt(args[0]); // get max number of tries
} catch (ArrayIndexOutOfBoundsException e) {
arg = "";
} catch (NumberFormatException e2) {
arg = "";
}
// try 'numTries' times to read a valid number input
for (int i=numTries; i > 0; --i) {
System.out.print("Please type in a positive whole number: ");
arg = user_input.next();
try {
value = Integer.parseInt(arg);
} catch(NumberFormatException e2) {
System.out.println("That's a letter! ");
continue;
}
if (value <= 0) {
System.out.println("That's a negative. ");
}
break; // exit loop if number input found
}
System.out.println("Input is " + value);
}
This code has been tested on IntelliJ and it runs with no problems.