I have an InputMismatchException which stops a decimal from being entered, but it doesn't help for negative integers/negative decimals.
if(userInput == 1) {
int l;
l = 0;
try {
l = input.nextInt();
} catch (InputMismatchException e) {
System.out.println("");
input.next();
}
}
If I add a do while loop with an if statement for anything equal to or less than zero it will loop within the if(userInput == 1) statement instead of starting from the beginning of the menu like it does if a positive decimal is entered. It also doesn't help for negative decimals.
I've tried to add two exceptions to the catch, but can't get that to work.
You could just turn your int into a String and check if it has a decimal point or a negative sign.
Scanner input = new Scanner(System.in);
int l;
while (true)
{
l = input.nextInt();
if ((""+l).indexOf('.') >= 0 || (""+l).indexOf('-') >= 0)
{
System.out.println(/*your message here*/);
}
else
{
break;
}
}
//continue with your program
Edit: Syntax
Try this:
if (input < 0){
throw new IllegalArgumentException("Input cannot be negative.");
}
If the number is negative, it will throw the exception and then the catch code can be executed.
Related
Just want to know if there was any better way of doing this since it's a lot of writing.
boolean isInputValid = false;
do {
System.out.print("Input: ");
final String input = sc.nextLine();
try {
age = Integer.parseInt(input);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
continue;
}
if (input < 0 || 10 < input) {
System.out.println("Number outside of range.");
} else {
isInputValid = true;
}
} while (!isInputValid);
Well there are some things that can be ommited on a first look, but there is not much to remove.
Reduced integer parsing in a single line and removed input variable.
Change isInputValid to its negation isInputInvalid to remove else , Boolean assignment and negation in the while clause.
Moved if into the try clause to make redundant and remove the continue statement.
boolean isInputInvalid = true;
do {
System.out.print("Input: ");
try {
age = Integer.parseInt( sc.nextLine());
isInputInvalid = input < 0 || 10 < input;
if (isInputInvalid) {
System.out.println("Number outside of range.");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
}
} while (isInputInvalid);
Well by first glance, I can see that you're comparing an incorrect variable type of string with an integer (your input variable), I'm just going to assume that you meant to compare the age. You should also put the if statements within your try/catch to ensure that its handled as intended (there's also no point in having it outside the try/catch if a NFE is thrown, it won't get ran anyways).
boolean isInputValid = true;
do {
System.out.print("Input: ");
final String input = sc.nextLine();
try {
age = Integer.parseInt(input);
if (age < 0 || 10 < age) {
System.out.println("Number outside of range.");
isInputValid = false;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Try again");
continue;
}
} while (isInputValid);
I am trying to write a method that asks a user for a positive integer. If a positive integer is not inputted, a message will be outputted saying "Please enter a positive value". This part is not the issue. The issue is that when I try to implement a try catch statement that catches InputMismatchExceptions (in case user inputs a character or string by accident), the loop runs infinitely and spits out the error message associated with the InputMistmatchException.
Here is my code:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
Essentially what is happening is that the scanner runs into an error when the given token isn't valid so it can't advance past that value. When the next iteration starts back up again, scanner.nextInt() tries again to scan the next input value which is still the invalid one, since it never got past there.
What you want to do is add the line
scanner.next();
in your catch clause to basically say skip over that token.
Side note: Your method in general is unnecessarily long. You can shorten it into this.
private static int nonNegativeInt() {
int value = 0;
while (true) {
try {
if ((value = scanner.nextInt()) >= 0)
return value;
System.out.println("Please enter a positive number");
} catch (InputMismatchException e) {
System.out.println("That is not a valid value");
scanner.next();
}
}
}
you are catching the exception but you are not changing the value of variable proper value so the catch statement runs forever. Adding properValue = true; or even a break statement inside the catch statement gives you the required functionality!
I hope I helped!
You can declare the scanner at the start of the do-while-loop, so nextInt() will not throw an exception over and over.
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
scanner = new Scanner(System.in);
try {
while (true) {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else if (variable >= 0) {
break;
}
}
properValue = true;
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
}
} while (properValue == false);
return variable;
}
This is indeed nearly identical to SO: Java Scanner exception handling
Two issues:
You need a scanner.next(); in your exception handler
... AND ...
You don't really need two loops. One loop will do just fine:
private static int nonNegativeInt(){
boolean properValue = false;
int variable = 0;
do {
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
continue;
} else if (variable >= 0) {
properValue = true;
}
} catch (InputMismatchException e){
System.out.println("That is not a valid value.");
scanner.next();
}
} while (properValue == false);
return variable;
}
Just add a break statement inside your catch.
Btw, you can get rid of the while loop by rewriting it like this:
try {
variable = scanner.nextInt();
if (variable < 0) {
System.out.println("Please enter a positive value");
} else {
properValue = true;
}
}
//...
This is a simple java function taking an input in double. It takes an input and first check if the value is non-numeric. And then check if the value is greater than 0 or not.
The problem I am facing is every time I enter a non-numeric input, it runs an infinite loop and only print "Enter a number greater or equal to 1.0: "
double getInput(double n) {
Scanner kbd = new Scanner(System.in);
boolean flag = false;
boolean check = false;
while (!flag) {
System.out.println("Enter a number greater or equal to 1.0: ");
try {
n = kbd.nextDouble();
if (n >= 0 || n < 0)
check = true;
} catch (InputMismatchException ex) {
err.print("Invalid Data Type (not Numeric)");
}
if (check == true) {
if (n < 0)
System.out.println("Invalid value (too small)");
else
flag = true;
}
}
return n;
}
kbd.nextDouble does not consume new line characters, hence these will be repeatedly passed into the while loop.
In your catch block instead of just throwing an exception, you can pass kbd.nextLine() so that for the next loop your input method is ready.
catch(InputMismatchException ex)
{
System.out.println("Invalid Data Type (not Numeric)");
kbd.nextLine();
}
Here is the complete code for you:
double getInput(double n)
{
Scanner kbd = new Scanner( System.in );
boolean flag =false;
boolean check = false;
while(!flag)
{
System.out.println("Enter a number greater or equal to 1.0: ");
try
{
n = kbd.nextDouble();
if(n>=0 || n<0)check = true;
}
**catch(InputMismatchException ex)
{
System.out.println("Invalid Data Type (not Numeric)");
kbd.nextLine();
}**
if(check==true)
{
if(n<0)
System.out.println("Invalid value (too small)");
else
flag = true;
}
}
return n;
}
Reading a double value from the scanner wont read the end of line
n = kbd.nextDouble();
so the scanner object will have something to read unless you get the line ending calling
kbd.nextLine();
the logic point to do this exactly after the exception comes...
catch (InputMismatchException ex) {
System.err.print("Invalid Data Type (not Numeric)");
kbd.nextLine(); ///here!!!
}
I'm new to Java, and I'm working on a method in my program that checks the users input to be within bounds, not a null value (zero), not a letter, and a positive number. So originally I incorporated two while loops within this method to check for the validity of these inputs, but I would like to simplify it in one loop. I'm getting an error when I input a letter (ex. a) after a few inputs, and I believe it is due to the two different while loops making it more complicated. Can someone help me with this please?
public static void valid(String s, int max)
{
while(sc.hasNextInt() == false) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
}
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
sc.nextLine();
return;
}
You have:
int value;
while((value= sc.nextInt()) > max || (value= sc.nextInt()) <= 0){
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
Which is doing sc.nextInt() twice, so value does not necessarily have the same value in these two cases and it is also asking you for a number twice.
A fix would be something like this:
int value;
while((value = sc.nextInt()) > max || value <= 0) {
System.out.println("That is not correct. Try again: ");
sc.nextLine();
}
which would make it better but you still have issues. If value is bigger than max, then the loop will iterate again calling nextInt() but this time you have not checked for hasNextInt(). This is why you'd better have everything in one loop. Something like this:
public static void valid(String s, int max) {
while(true) {
if(!sc.hasNextInt()) { //this is the same as sc.hasNextInt() == false
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop again
} else {
int value = sc.nextInt();
if(value > max || value <= 0) {
System.out.println("That is not correct. Try again:");
sc.nextLine();
continue; //restart the loop from the top - important!
} else {
extendedValidation(value, s);
return;
}
}
}
}
Try something more like (pseudo code):
while valid input not yet received:
if input is an integer:
get integer
if in range:
set valid input received
skip rest of line
extended validation
With a little thought, you should be able use one "print error message" statement. But using two could be arguably better; it can tell the user what they did wrong.
What is the purpose of the String s parameter? Should you be checking that instead of a Scanner input?
Also, don't be surprised by mixing nextInt() and nextLine(). -- Source
I prefer using do-while loops for input before validation.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int max = 1000;
int val = -1;
String in;
do {
// Read a string
System.out.print("Enter a number: ");
in = input.nextLine();
// check for a number
try {
val = Integer.parseInt(in);
} catch (NumberFormatException ex) {
// ex.printStackTrace();
System.out.println("That is not correct. Try again.");
continue;
}
// check your bounds
if (val <= 0 || val > max) {
System.out.println("That is not correct. Try again.");
continue;
} else {
break; // exit loop when valid input
}
} while (true);
System.out.println("You entered " + val);
// extendedValidation(value, in);
}
I would say that this is a lot closer to what you're looking for, in simple terms...
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
final int MIN = 0;
final int MAX = 10;
Scanner sc = new Scanner(System.in);
int value = -1;
boolean valid;
do {
valid = sc.hasNextInt();
if (valid) {
value = sc.nextInt();
valid = value > MIN && value < MAX;
}
if (!valid) {
System.out.println("Invalid!");
sc.nextLine();
}
} while (!valid);
System.out.println("Valid Value: " + value);
}
}
You should be able to abstract this code to suit your requirements.
im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i