I remember having this exact issue in Python. This Java code is a replica of my Python code which calculates the area of a triangle. I have it catch an exception if a non-number value is entered, but the end result gets botched.
private static float baseLength() {
float baseLength = 0;
Scanner user_input = new Scanner(System.in);
try {
while (baseLength <= 0) {
System.out.print("Enter the base length of the triangle: ");
baseLength = user_input.nextFloat();
if (baseLength <=0) {
System.out.println("Error. Plase enter a number higher than 0.");
}
}
} catch (InputMismatchException badChar) {
System.err.println("You have entered a bad value. Please try again");
baseLength();
}
return baseLength;
It will recover from bad numbers, but not from a value that is not a number. I still can't figure out what the exact issue is.
You can put the while loop around the try/catch block to achieve this:
private static float baseLength() {
float baseLength = 0;
Scanner user_input = new Scanner(System.in);
while (baseLength <= 0) {
try {
System.out.print("Enter the base length of the triangle: ");
baseLength = user_input.nextFloat();
if (baseLength <= 0) {
System.out.println("Error. Plase enter a number higher than 0.");
}
} catch (InputMismatchException badChar) {
System.err.println("You have entered a bad value. Please try again");
}
}
return baseLength;
}
with tests more clear, and exception inside principal loop, and every errors with System.err
private static float baseLength() {
float baseLength = 0;
while (true)
{
try {
System.out.print("Enter the base length of the triangle: ");
Scanner user_input = new Scanner(System.in);
baseLength = user_input.nextFloat();
if (baseLength>0)
return baseLength;
if (baseLength <=0)
System.err.println("Error. Plase enter a number higher than 0.");
}
catch (InputMismatchException badChar)
{
System.err.println("You have entered a bad value. Please try again");
}
}
}
Related
I'm making a very simple program that asks a user to input an age and then it will calculate a charge for admission. So far all works well but I'm wanting to add a check in so that if the user inputs anything other than an int value, it will ask them to enter an int value. I.e if they enter a character.
Here is my code:
public class CalcChargeAge {
public static void main(String[] args) {
int x;
double chargeA = 20;
double chargeB = 10;
System.out.println("Enter Users age to calculate charge for entry. ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if (x >= 18) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeA);
} else if (x >= 12) {
System.out.println("Users age is " + x);
System.out.println("Please pay the charge for entry: £" + chargeB);
} else {
System.out.println("Users age is " + x);
System.out.println("User entry charge is free. Print admission ticket.");
}
}
}
You can use the Scanner.hasNextInt() method to check whether the input is an integer, which I think is a lot nicer than catching an exception.
Then for the full implementation you could wrap everything in a loop, so you could do something like:
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
if(in.hasNextInt()) {
int x = in.nextInt();
// Handle input
break;
}
else {
// Handle invalid input
in.next();
}
}
Something like this should work fine:
boolean isValid = false;
int validInput = 0;
while (!isValid) {
try {
validInput = scanner.nextInt();
isValid = true;
}
catch (Exception e) {
System.out.println("Please enter a valid integer.");
}
}
// ... code using validInput
One of the ways (beware, it might not be the best or even the good one) to go about it would be to replace x=in.nextInt(); with
while(true) {
String input = in.next();
try {
x = Integer.parseInt(input);
break;
} catch (Exception e) {
System.out.println("Please provide an integer!");
}
}
this will not leave the loop until user provides an integer value (evil!)
I am wishing to prompt the user again if a double outside of the accepted range (0-100) is input, until the input is valid. When the input is considered valid, I am wanting to return correct input value, yet, returned instead is the first incorrect value. How can I return the correct input, as accepted by the if statement?? Many thanks!
public class examscore {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
double sumfin = finalscore(console);
System.out.println(sumfin); // if user input is initially invalid, but then corrected, the first, incorrect, value is printed
}
public static double finalscore (Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
while(!console.hasNextDouble()) { //prompts the user, if invalid input, to input again, until a valid value is input
System.out.println("Please input a mark between 0 and 100. ");
console.next();
}
double examscore = console.nextDouble();
if (examscore >=0 && examscore<= 100) {
System.out.println();
System.out.println("Exam Score = "+examscore);
} else {
System.out.println("Error:");
finalscore (console);
}
return examscore; //an attempt to return the VALID exam score: fails
}
}
A do-while loop would be a perfect fit. Example:
Scanner console = new Scanner(System.in);
double userInput = 0;
do {
System.out.println("Please input a mark between 0 and 100. ");
try {
userInput = console.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Your input could not be interpreted as a floating-point number.");
}
} while (userInput <= 0D || userInput >= 100D);
You missed to assign result of finalscore(console) to examscore inside the else block.
if (examscore >= 0 && examscore <= 100) {
System.out.println();
System.out.println("Exam Score = " + examscore);
} else {
System.out.println("Error:");
examscore = finalscore(console);
}
You can either use a loop or a recursive call to accomplish this. I prefer a recursive call:
private static double getValidScore(Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
try {
double score = Double.parseDouble(console.nextLine());
if (score >= 0 && score <= 100) {
return score;
}
} catch (NumberFormatException nfe) {}
System.out.println("Please input a mark between 0 and 100.");
return getValidScore(console);
}
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 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.");
}
}
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!");
}
}
}