I am writing a simple part of a program where the user gives the year being born. The code is as follows:
while(true){
try {
year = input.nextInt();
break;
} catch (InputMismatchException mismatchException) {
System.err.println("year of birth can only have numbers");
}
}
So what happens is if i give a valid int (year is of type int) everything is ok. If i give a string like "hello" what i expected it to do is to get again inside try and ask me for a number after it has written the error message.
Is my way of thinking wrong concerning try - catch statement?
Try this ( I guess input is java.util.Scanner):
while(input.hasNext()) {
if (input.hasNextInt()) {
year = input.nextInt();
break;
} else {
System.out.println("year of birth can only have numbers");
input.next();
}
}
input.close();
You have to try this so you can get the next input, if you dont give a number:
Scanner input = new Scanner(System.in);
int year;
boolean repeat = true;
while(repeat){
try {
repeat = false;
year = input.nextInt();
} catch (InputMismatchException mismatchException) {
System.err.println("year of birth can only have numbers");
input.next();
repeat = true;
}
}
System.out.println("DONE");
Related
Why input.nextLine() keeps running the catch block when I'm inputting a value which is not an integer? And why it is not running from input.nextInt when I'm inputting an Int value in input.nextLine()?
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionHandlingEg01 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = 0;
do{
try{
num = input.nextInt();
if(num != -1) {
System.out.println("You Entered " + num + "\nEnter -1 to exit: ");
}
else {
System.out.println("Program Exited");
}
} catch (InputMismatchException e) {
e.printStackTrace();
System.out.println("Please Enter a number");
input.nextLine();
}
} while (num != -1);
}
}
Your code moves to the catch block because your code requested an integer, but you didn't enter an integer. This is normal and expected behaviour.
It looks like you may have mis understood how the catch block works. Here is a correctly functioning version of your code that asks for a number at the start of your do/while loop:
Scanner input = new Scanner(System.in);
int num = 0;
do{
//Move the question to the top of the loop
System.out.println("Please Enter a number");
try{
num = input.nextInt();
if(num != -1) {
System.out.println("You Entered " + num + "\nEnter -1 to exit: ");
}
else {
System.out.println("Program Exited");
}
}
//This will only be called if an invalid input is entered
//Once the catch block is complete the loop will run again and ask for another number
catch (InputMismatchException e) {
e.printStackTrace();
//Print the fail message here
System.out.println("That was not a number");
//The below line was removed, this is not the correct place for it. The loop already reads the number at the start
//input.nextLine();
}
} while (num != -1);
Caution: Be very careful when using next methods like nextInt() with nextLine(), your code will not read correct inputs, see here for more information: Scanner is skipping nextLine() after using next() or nextFoo()?
Java beginner here. Im trying to create a do while loop where the user is supposed to key in some info. If the user keys in the correct info for something_A, the program should move on to asking user to key in info for something_B.
If the user enters incorrect info for this, the program should throw the respective exception which is InvalidExcep_B. I can get all this to work except once the exception is thrown, the program prompts the user to key in info from the beginning.
What should I do in order for the program to keep prompting only to input the piece of info that was incorrect?
boolean continueInput = true;
userInput = new Scanner (System.in);
System.out.println();
do {
try {
System.out.print("Enter Something_A: ");
something_A = userInput.nextInt();
if (condition ok) {
run statements;
}
System.out.print("Enter Something_B: ");
something_B = userInput.nextInt();
if (condition ok) {
run statements;
}
System.out.print("Enter Something_C: ");
something_C = userInput.nextInt();
if (condition ok) {
run statements;
}
continueInput = false;
}
catch (InvalidExcep_A e) {
System.out.println(e.toString());
continueInput = true;
}
catch (InvalidExcep_B e) {
System.out.println(e.toString());
continueInput = true;
}
catch (InvalidExcep_C e) {
System.out.println(e.toString());
continueInput = true;
}
} while (continueInput == true);
System.out.print("Enter Something_D: ");
something_D = userInput.next();
printInfo (parameters);
}
This is what I have so far. Thank you!
A couple things you could try.
Separating the do-while per input (right now, you have it all in one do-while). A bit repetitive but hey, it gets the job done.
Store a list of [input, actions] and just iterate through that in your while loop, the stop condition being once you finish that list.
You code is almost correct except since we need to remember whether Something_A is already finished or not. Similarly, for Something_B and Something_C we have to remember whether it is finished or not. So, the condition for Something_A, Something_B and Something_C should be different. Hence I chose conditionA, conditionB and conditionC for Something_A, Something_B and Something_C respectively.
The following code should solve your problem:
boolean continueInput = true;
boolean conditionA = true, conditionB = true, conditionC = true;
Scanner userInput = new Scanner (System.in);
System.out.println();
int somethingA = -1, somethingB = -1, somethingC = -1;
String somethingD = "";
do {
try {
if (conditionA) {
System.out.print("Enter Something_A: ");
somethingA = userInput.nextInt();
// runStatementsA();
conditionA = false; // Will not prompt for Something_A again.
}
if (conditionB) {
System.out.print("Enter Something_B: ");
somethingB = userInput.nextInt();
// runStatementsB();
conditionB = false; // Will not prompt for Something_B again.
}
if (conditionC) {
System.out.print("Enter Something_C: ");
somethingC = userInput.nextInt();
// runStatementsX();
conditionC = false; // Will not prompt for SOmething_C again.
}
continueInput = false;
} catch (java.util.InputMismatchException e) { // Replace 'java.util.InputMismatchException' with 'InvalidExcep_A'
System.out.println(e.toString());
userInput.next(); // Flush the scanner object
} catch (java.lang.NullPointerException e) { // Replace 'java.lang.NullPointerException' with 'InvalidExcep_B'
System.out.println(e.toString());
userInput.next(); // Flush the scanner object
} catch (java.lang.RuntimeException e) { // Replace 'java.lang.RuntimeException' with 'InvalidExcep_C'
System.out.println(e.toString());
userInput.next(); // Flush the scanner object
}
} while (continueInput == true);
System.out.print("Enter Something_D: ");
somethingD = userInput.next();
//printInfo(parameters);
I am trying to learn try-catch uses and have to validate input so that the user must enter 1 or 2 for the program to continue. I believe I am close, but cannot seem to get the program to continue if the user enters something wrong such as '3' or '2.12'.
Here's what I have:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
I don't necessarily see the point of using InputMismatchException for your use case. Instead, if the input doesn't match what you expect, you can log an error and just prompt the user to input again.
But [Integer#parseInt()][1] can throw an exception if the input isn't an actual integer. In your original code you never actually use the result of this call, but I have done so in my answer. In this case, it does potentially make sense to use a try-catch block.
int result;
while (true) {
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
result = Integer.parseInt(input);
} catch(Exception e) {
System.out.println("Could not parse input, please try again.");
continue;
}
if (result != 1 && result != 2) {
System.out.println("Invalid input! Please select '1' or '2':");
}
else {
break;
}
}
You should put in your condition the throw statement in able to your catch statement fetch the error, the code should be like this:
String input = " ";
try {
Scanner scan = new Scanner(System.in);
input = scan.next();
Integer.parseInt(input);
if (!input.equals("1") && !input.equals("2")) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
throw new InputMismatchException ();
}
} catch (InputMismatchException a) {
System.out.println();
System.out.println("Invalid imput! Please select '1' or '2':");
}
The code is expecting for positive integers but can input string and loop again until got a positive integer input value.
Scanner scanner = new Scanner(System.in);
Integer expectedOutput = -1;
public Integer getInputNumber(){
boolean valid;
String inputData;
do {
System.out.print("Enter Input Number: \t");
try {
inputData = scanner.nextLine();
// expecting positive integers
if (Integer.parseInt(inputData) > 0) {
expectedOutput = Integer.parseInt(inputData);
valid = true;
} else {
System.out.println("Invalid Input!");
valid = false;
}
} catch (Exception ex){
valid = false;
}
} while(!valid);
return expectedOutput;}
I'm sure this is something simple that I just can't spot, I have a do while loop prompting the user for an array size, which will be used for the rest of the program. If the user enters the right input, the program continues and works fine, but if the user enters the wrong input...
public static void main(String[] args)
{
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do
{
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
}
catch(InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
If the user enters an invalid input, such as "red", the catch block kicks in and prints "Make sure to enter a valid number." and "Enter an array size." over and over without giving the user a chance to actually enter any input. I figured resetting the arraySize variable would fix it, but it doesn't. I guess the keyboard buffer has stuff in it, but no combination of empty printlns has worked so far.
I've heard that Exceptions shouldn't be used to validate user input. Why is that?
Regardless, it's not relevant to this question, as it is an exercise in Exception handling.
Without using isValid boolean variable and make simple code for input.
int arraySize = 0;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) throw new NegativeArraySizeException();// for negative arry size
break;// loop break when got a valid input
} catch (Exception mistake) {
System.err.println("Invalid input: " + mistake);
}
} while (true);
You can add a keyboard.nextLine(); in the event of exception and it should resolve the issue.
try {
arraySize = keyboard.nextInt();
}
catch(NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
catch(Exception mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
keyboard.nextLine();
}
Please see if this fix works for you. Scanner has a problem when you are trying to get the string from nextInt function. In this I have fetched the string and parsed to Integer and then handled the Number format exception
public static void main(String[] args) {
// user enters up to 20 double values, stored in an array, user should enter 99999 to quit entering numbers. If user has not entered any numbers yet
// display an error message, otherwise, display each entered value and it's distance from the average
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
isValid = true;
arraySize = 0; // reset these values at start of each loop.
System.out.println("Enter an array size.");
try {
arraySize = Integer.parseInt(keyboard.next());
} catch (NegativeArraySizeException mistake) {
System.out.println("Do not enter a negative number for the arrays size.");
System.out.println();
isValid = false;
} catch (InputMismatchException mistake) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
} catch (NumberFormatException nfe) {
System.out.println("Make sure to enter a valid number.");
System.out.println();
isValid = false;
}
} while (isValid == false);
}
mmuzahid is almost there. But I added a way of checking negative number as well. Try this
Scanner keyboard = new Scanner(System.in);
int arraySize = 0;
boolean isValid = false;
do {
System.out.println("Enter a valid array size.");
try {
arraySize = Integer.valueOf(keyboard.nextLine());
if (arraySize < 0) {
System.out.println("Make sure to enter a valid positive number.");
} else {
break;
}
} catch (Exception mistake) {
System.out.println("Make sure to enter a valid number. Error:" + mistake);
}
} while (true);
Use keyboard.nextLine() and NumberFormatException
do {
// more code
try {
arraySize = Integer.valueOf((keyboard.nextLine()));
} catch (NegativeArraySizeException mistake) {
// more code
isValid = false;
} catch (InputMismatchException mistake) {
// more code
isValid = false;
} catch (NumberFormatException mistake) {
// more code
isValid = false;
}
} while (isValid == false);
I'm trying to make a program that gets a number from the user and checks the number is a prime number or not. I was thinking about the error handling. When the user enters a string the program should give an error message instead of an exception. I tried many methods but couldn't be successful. Could you guys help me with that?
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
if(inputNum < 0){
System.out.println("Please enter a possitive number.");
}
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
}
If user enters a non-integer input, this line
inputNum = input.nextInt();
will throw an exception (an InputMismatchException). The way Java handles exceptions is through a try-catch block:
try {
inputNum = input.nextInt();
// ... do domething with inputNum ...
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
Note: If you want to know more about exceptions (and you must) you can read Java tutorials.
just put it in try-catch and then print your message when exception occurs mean in the catch clause..its simple thing
If you need to check the input first and if it is a number check for prime and if it is invalid prompt user for another input until he enter a valid one, try this.
String inputString;
boolean isValid = false;
while(isValid == false){
//sysout for input
inputString = input.nextLine();
if(inputString.matches("[0-9]+")){
// check for prime
isValid = true;
}else{
//printin error
}
}
}
Thank you to every one especially to Christian. Here is the latest code.
import java.util.InputMismatchException;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
int inputNum;
int remainingNum;
System.out.println("Enter a number: ");
inputNum = input.nextInt();
for(int i = 2; i<=inputNum; i++) {
remainingNum = inputNum % i;
if(remainingNum == 0){
System.out.println("This number is not a prime number.");
break;
}
if(remainingNum == 1){
System.out.println("This is a prime number!");
break;
}
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
}
}
}