I've finished a simple program that converts a decimal number to binary (32bit). I would like to implement some type of error message should the user enter in an overflow number (anything over 2147483647). I tried a if_else , loop, but quickly found out I couldn't even do that. So I messed with taking the input as a string, and then using some things like .valueOF() etc, and still can't seem to get around to the solution.
I don't see how I can compare any value to a >2147483648 if I can't store the value in the first place.
Here's the bare code I have for the getDecimal() method:
numberIn = scan.nextInt();
Edit:: After trying the try / catch method, running into a compile error of
"non-static method nextInt() cannot be referenced from a static context".
My code is below.
public void getDec()
{
System.out.println("\nPlease enter the number to wish to convert: ");
try{
numberIn = Scanner.nextInt();
}
catch (InputMismatchException e){
System.out.println("Invalid Input for a Decimal Value");
}
}
You can use Scanner.hasNextInt() method, which returns false, if the next token cannot be converted to an int. Then in the else block, you can read the input as string using Scanner.nextLine() and print it with an appropriate error message. Personally, I prefer this method :
if (scanner.hasNextInt()) {
a = scanner.nextInt();
} else {
// Can't read the input as int.
// Read it rather as String, and display the error message
String str = scanner.nextLine();
System.out.println(String.format("Invalid input: %s cannot be converted to an int.", str));
}
Another way to achieve this is of course, using try-catch block. Scanner#nextInt() method throws an InputMismatchException, when it can't convert the given input into an integer. So, you just need to handle InputMismatchException: -
try {
int a = scan.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid argument for an int");
}
I suggest you surround that statement with a try/catch block for NumberFormatException.
Like so:
try {
numberIn = Integer.valueOf(scan.next());
}catch(NumberFormatException ex) {
System.out.println("Could not parse integer or integer out of range!");
}
use exceptions.. whenever a number is entered more than its storing capacity then exception will be raised
Refer docs.oracle.com/javase/tutorial/essential/exceptions/
You can user hasNextInt() method to make sure that there is an integer ready to be read.
try this :
long num=(long)scan.nextLong();
if (num > Integer.MAX_VALUE){
print error.
}
else
int x=(int)num;
or try catch:
try{
int number=scan.nextInt()
}
}catch(Exception ex){
print the error
}
Related
If the user enter a non-numeric value for example "Hello", I want to give the user a new chance to enter a numeric value until he succeeds.
Running the code below, the text "This is not a numeric value. Enter a numeric value: ", will show in the console, if the user enters a non-numeric value. However, the user will not be able to enter a new value. Because the error message "Exception in thread..." will show and stop the program.
How do I solve this?
Edit!
New code (This code works, except it stops the program completely. Every method called afterwards, won't run.) Edit2! It did not work!
int number;
do {
try {
System.out.println("Enter a numeric value: ");
number = Integer.parseInt(s.nextLine());
if (s.nextInt() != (int)number) {
throw new NumberFormatException();
}
break;
}
catch (NumberFormatException e) {
System.out.println("This is not a numeric value. Enter a numeric value: ");
}
} while (true)
Old code
int number;
try {
Scanner s = new Scanner(System.in);
System.out.println("Enter a numeric value: ");
number = s.nextInt();
if (number != (int)number) {
throw new Exception();
}
}
catch(Exception e) {
do {
System.out.println("This is not a numeric value. Enter a numeric value: ");
number = s.nextInt();
} while (number != (int)number);
}
Use NumberFormatException instead of Base Exception Class
int number;
Scanner s = new Scanner(System.in);
System.out.println("Enter a numeric value: ");
do {
try {
number = Integer.parseInt(s.nextLine());
//Do your work
break;
} catch (NumberFormatException e) {
System.out.println("This is not a numeric value. Enter a numeric value: ");
}
}
while (true);
}
Please try below given code:
int number;
Scanner s = new Scanner (System.in);
System.out.println ("Enter a numeric value: ");
do
{
try
{
number = Integer.parseInt (s.nextLine ());
//Do your work
break;
}
catch (Exception e)
{
System.out.println
("This is not a numeric value. Enter a numeric value: ");
}
}
while (true);
}
It sounds like you want to loop forever until the user enters a valid integer. A common way to express "loop forever" is with while (true) {...}. This is an "infinite loop." The only way to exit this loop is with a break statement or a return statement (or by throwing an exception, but in this case you want to catch the exception and continue looping).
One problem with using scanner.nextInt() is that if the value is not an integer, the value will remain in the scanner's buffer. If you keep calling nextInt(), you'll just keep getting InputMismatchExceptions since the scanner will keep trying to interpret the same bad input as an integer, over and over again.
One way around that problem is to use scanner.nextLine() to read the value as a String, and then use Integer.parseInt(String) to convert the String to an int. If the conversion fails, Integer.parseInt(String) throws a NumberFormatException. You can handle this exception by catching it.
Here's a little function that loops forever until the user enters a value that can be parsed as an int:
public static int promptForInt(Scanner scanner) {
while (true) {
System.out.println("Enter a numeric value:");
try {
return Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.print("This is not a numeric value. ");
}
}
}
You can call the method like this:
Scanner scanner = new Scanner(System.in);
int number = promptForInt(scanner);
I don't think you truly understand where the exception is coming from. The line throw new Exception(); never runs in your code. This is because your if statement says if (number != (int) number), which will never be true because the variable number is already of the type int, so you are basically saying if (number != number), which can never be true. If you take a look at Scanner's nextInt() method, you'll notice that it actually throws InputMismatchException. That is the exception you are catching with your try-catch, but it is not the exception that is causing the error message. So where is that exception coming from? The line number = s.nextInt(); is not compilable code. You defined s inside the try block, so therefore s only exists inside the try block. You get an exception when you try to access it in the catch block because s is not a variable there; it does not exist as far as the compiler is concerned. The fix is pretty simple; just move the declaration for s to outside the try block, and put the while loop around the try-catch block. Also remember to consume the line separators in the input stream using s.nextLine() every time you try to read an int. Here's an example of how I would do it:
int number;
Scanner s = new Scanner(System.in); //declare s outside of the try block
System.out.println("Enter a numeric value: ");
while (true) { //while loop goes around the try-catch block
try {
number = s.nextInt(); //this could throw InputMismatchException
break; //if no exception is thrown, break out of the loop
} catch (InputMismatchException e) { //if the exception is thrown
s.nextLine(); //consume the line separator character(s)
System.out.println("This is not a numeric value. Enter a numeric value: "); //prompt the user for another value
//this will then go back to the top of the try block again, because we never broke out of the while loop
}
}
s.nextLine(); //consume the line separator character(s)
Try the following, if you take your input as a string you can parseInt to check if its an integer value
String number = null;
Scanner s = new Scanner(System.in);
System.out.println("Enter a numeric value: ");
number = s.next();
try {
// checking valid integer using parseInt() method
Integer.parseInt(number);
} catch (NumberFormatException e) {
System.out.println("This is not a numeric value. Enter a numeric value:");
number = s.next();
// put this line here to prove it accepted the second attempt
System.out.println("Your entered integer is:" + number);
}
s.close();
}
}
I'm writing a program that culculates tip and total from bill and tip rate.
public void takeUserInput() {
Scanner sc = new Scanner(System.in);
double billAmount;
int tipRate;
try {
System.out.print("What is the bill? ");
billAmount = sc.nextDouble();
System.out.print("What is the tip percentage? ");
tipRate = sc.nextInt();
tc.calculate(billAmount, tipRate);
} catch (InputMismatchException e1) {
String errorMessage = "Please enter a valid number for the ";
// errorMessage += billAmount or
// errorMessage += tipRate ?
}
I'm looking for a way to find out which variable throws InputMismatchException, so I can add which variable name into variable errorMessage and print to the screen.
There are various simple ways to get there:
Call hasNextXxx() prior calling nextXxx().
If you go for one try/catch block per input, it is very clear within your catch block which variable caused the problem (you could then call a generic method with a specific error message to avoid code duplication)
You could use reference types for your variables; if you use Double / Integer instead of double / int ... you could check which of the two variables is still null
You put in a little boolean variable, like billAmountIsValid. Initially that variable is false, you turn it to true after the call to nextDouble(). Then you can easily check in your try block whether you got a valid billAmount.
After some more thinking: you really want a combination of 1 + 2: you see; when the users enters a correct billAmount; why would you want to forget about that value when the second value gives a bad second value? No - you should be looping for each variable, until you receive a valid input. And only then you start asking for the next value!
The variable isn't throwing the exception, the evaluation of the right hand side of the variable assignment is, and so there is no information in the exception to say which variable it was about to assign that to had it succeeded.
What you could consider instead is a new method that encompasses the prompting messages and retries:
billAmount = doubleFromUser(sc, "What is the bill? ", "bill");
Where doubleFromUser is:
static double doubleFromUser(Scanner sc, String prompt, String description){
while(true) { //until there is a successful input
try {
System.out.print(prompt); //move to before the loop if you do not want this repeated
return sc.nextDouble();
} catch (InputMismatchException e1) {
System.out.println("Please enter a valid number for the " + description);
}
}
}
You will need a different one for int and double, but if you have more prompts, you will save in the long run.
I want to make a try-catch exception that only accept 1-5 or 9 input. So I wrote the following code.
try {
step1 = scanner.nextInt();
} catch (Exception ex) {
System.out.println("Error! Input accept integers only. Input 1-5 or 9");
System.out.println("");
continue;
}
The result is that if I input an invalid number, it gave me an error (That's true). But when I input a character, it gave me an infinite loop. How can I solve the problem?
Since i don´t know how your loop looks i´ll just go with an endless loop in my answer. In the normal case, the nextInt method wont catch the carriage return, and if you input something that is not a number you need to call nextLine to catch this. If you don´t do this you might run into an infinity loop if you are using any kind of loop that just asks for nextInt. This could solve the problem:
while(true) {
int step1;
try {
step1 = s.nextInt();
} catch (InputMismatchException e) {
System.out.println("Error! Input accept integers only. Input 1-5 or 9");
System.out.println("");
} finally { // Use a finally block to catch the carriage return, no matter if the int that got input was valid or not.
s.nextLine();
}
}
Maybe you must parse input before decision making.
Sorry for my bad English, I'm not a native speaker also.
try this, which make all the tests
int step1;
while (true)
{
Scanner scanner = new Scanner(System.in);
try {
step1 = scanner.nextInt();
if (((step1>=1) && (step1<=5)) || (step1==9))
// BINGO
break;
}
catch (Exception ex)
{
}
System.out.println("Error! Input accept integers only. Input 1-5 or 9");
System.out.println("");
// it loops ther
}
System.out.println("You are done ! "+step1);
Here is my code for inputting a student number:
When the user inputs the number in a unexpected format I will ask them to reinput by recursion. But it ends up with an infinitive recursion. Why?
private static int inputStudentNumber(){
System.out.println("Enter the student number:");
int studentNum;
try {
//Scanner in initialized before calling this method
studentNum = in.nextInt();
return studentNum;
} catch(Exception e) {
System.out.println("Invalid input, it can only be integer.");
return inputStudentNumber();
}
}
Take a closer look at the javadocs for Scanner.nextInt:
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. (emphasis added)
If it's not successful, the scanner isn't advanced. That means that if you try to invoke nextInt() again, you'll be trying to get an int from the same token as before, and you'll once again get an InputMismatchException.
Your code basically says: try to read the next token as an int. If that fails, recurse to try to read the token as an int again. If that fails, recurse to try to read the token as an int again. If that fails... (and so on, until you get a StackOverflowException from too much recursion).
If you want to use recursion for this, you should probably use next() to skip to the next token. And only catch InputMismatchException, so that you won't also catch NoSuchElementException (which won't happen for System.in, but is good practice in general -- what if you later decide to read from a file, and that file has reached its end?).
} catch(InputMismatchException e) {
System.out.println("Invalid input, it can only be integer.");
in.next(); // skip this token
return inputStudentNumber();
}
An even better approach would be to avoid using the exception to control your logic in the first place. To do this, you'd have to know ahead of time whether nextInt will succeed. Luckily for you, hasNextInt() lets you do exactly that!
private static int inputStudentNumber() {
System.out.println("Enter the student number:");
if (in.hasNextInt()) {
return in.nextInt();
} else {
System.out.println("Invalid input, it can only be integer.");
in.next(); // consume the token
return inputStudentNumber();
}
}
The advantage here -- besides the general "don't use exceptions for control flow" advice -- is that the base case is super clear. If there's an int ready, that's your base case; if not, you have to advance the scanner and try again.
The problem is that if a non-integer is entered as input, then that input is not consumed by the scanner. So you just keep reading it.
You may want to just read the input as a string and then try to convert it separately.
Your problem is probably that in.nextInt() is throwing an Exception. A code smell that I see is that you use:
catch(Exception e) {
....
}
The best practice here is to only catch the specific Exception you are expecting, so it should be:
catch(InputMismatchException e) {
....
}
If you do this, then whatever in.nextInt() is throwing will properly propagate to the top, and you will probably see that in is not initialized or some such problem.
See here for the Exceptions that nextInt() can throw.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()
try this...
private static int inputStudentNumber(){
System.out.println("Enter the student number:");
int studentNum;
int var = 1;
while(var ==1)´
{
try{
studentNum = in.nextInt();
var=0;
return studentNum;
}catch(Exception e){
System.out.println("Invalid input, it can only be integer.");
var=1;
return inputStudentNumber();
}
}
}
I am making a simple program that lets you add the results of a race, and how many seconds they used to finish. So to enter the time, I did this:
int time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
So my question is, how can I display an error message to the user if he enters something other than a positive number? Like a MessageDialog that will give you the error until you enter a number.
int time;
try {
time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
} catch (NumberFormatException e) {
//error
}
Integer.parseInt will throw a NumberFormatException if it can't parse the int.
If you just want to retry if the input is invalid, wrap it in a while loop like this:
boolean valid = false;
while (!valid) {
int time;
try {
time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
if (time >= 0) valid = true;
} catch (NumberFormatException e) {
//error
JOptionPane.showConfirmDialog("Error, not a number. Please try again.");
}
}
Integer.parseInt Throws NumberFormatException when the parameter to Integer.parseInt is not a integer, Use try Catch and display required error message, keep it in do while loop as below
int time = -1;
do{
try{
time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
}
catch(NumberFormatException e){
}
}while(time<=0);
If JOptionPane.showInputDialog("Enter seconds") is not a valid number, you will be getting NumberFormatException.For positive number check, just check time >=0
Depends on how you want to solve it.
An easy way is to declare time as an Integer and just do:
Integer time;
while (time == null || time < 0) {
Ints.tryParse(JOptionPane.showInputDialog("Enter seconds"));
}
Of course that would require you to use google guava. (which contains a lot of other useful functions).
Another way is to use the above code but use the standard tryparse, catch the NumberFormatException and do nothing in the catch.
There are plenty of ways to solve this issue.
Or not reinvent the wheel and just use:
NumberUtils.isNumber or StringUtils.isNumeric from Apache Commons Lang.