Hey there! I'm trying to do some data input validation but I haven't been able to figure it out. I'm getting an infinite while loop in when I try to validate if the first character entered is a letter. . . .
Thanks for your help!
public class methods
{
public static void main(String args[]) throws IOException
{
String input ="";
int qoh=0;
boolean error=true;
Scanner keyboard = new Scanner (System.in);
//while (error)
//{
//error=true;
while (error==true)
{
System.out.print("\nEnter Quantity on Hand: ");
input = keyboard.nextLine();
if (input.length() <1)
{
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
error=true;
System.out.println(qoh);
System.out.println(input);
}
else
{
error=false;
}
}
error = true;
while (error==true)
{
if (Character.isLetter(input.charAt(0)))
{
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
error=true;
System.out.println(qoh);
System.out.println(input);
}
else
{
qoh = Integer.parseInt(input);
error=false;
}
}
}
}
You don't have an input = keyboard.nextLine(); in your second while loop.
You could refactor your code to only ask for new input when there is an error. So right after the sysout of 'ERROR...'
Extra:
I would actually do this different. The 'error = true' at the beginning is a bit confusing, because there might not be an error.
You could for example write a method called tryProcessLine, which reads the input and returns true if ok and false if there was an error, and than just do something like while(!tryProcessLine()){ }
Working example below:
import java.io.IOException;
import java.util.Scanner;
public class Methods {
private static int qoh;
public static void main(String args[]) throws IOException {
while (!tryProcessLine()) {
System.out.println("error... Trying again");
}
System.out.println("succeeded! Result: " + qoh);
}
public static boolean tryProcessLine() {
String input = "";
Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter Quantity on Hand: ");
input = keyboard.nextLine();
try {
qoh = Integer.valueOf(input);
if (qoh < 0 || qoh > 500) {
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
return false;
} else {
return true;
}
} catch (NumberFormatException e) {
System.out.println("\n**ERROR06** - Quantity on hand must be numeric");
return false;
}
}
}
The problem is in this section:
while (error==true)
{
if (Character.isLetter(input.charAt(0)))
{
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
error=true;
System.out.println(qoh);
System.out.println(input);
}
else
{
qoh = Integer.parseInt(input);
error=false;
}
}
Once you have a letter in the first position, this loop can never terminate. It checks whether a letter is in the first position (it is), prints it, and repeats. Try changing to:
while (error==true)
{
if (Character.isLetter(input.charAt(0)))
{
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
error=false;
...
Also, a couple of other things:
while (error == true) can be shortened to while(error).
Also, Integer.parseInt will throw a NumberFormatException if the input is not an integer - you need to catch and handle this.
Also, why do you need the second loop at all? It seems like it is only supposed to validate the input - if so, you can move this logic into the first loop and eliminate the second one. Only use loops for things that should happen repeatedly (like the user entering input data). There is no need to check the same input repeatedly.
The infinite loop occurs because the second while loop is repeatedly checking whether the first character in the String (input.charAt(0)) is a letter. Assuming that the result from this check is true the loop will never terminate.
Your code could be simplified to something like:
Integer qty = null;
while (scanner.hasNext() && qty == null) {
String line = scanner.next();
try {
qty = Integer.parseInt(line);
} catch(NumberFormatException ex) {
System.err.println("Warning: Ignored non-integer value: " + line);
}
}
if (qty == null) {
System.err.println("Warning: No quantity specified.");
}
If it is a character, you're allowing error to still = true, which is causing that loop to continue forever, you're not ever going back to the beginning and reading another line.
Here is some code that does what you want and is structured a little better.
public class ScanInfo {
Scanner keyboard = new Scanner(System.in);
public ScanInfo(){
String line = getLineFromConsole();
while(null != line && !"quit".equals(line)){
if(isValidInput(line)){
int validNumber = Integer.parseInt(line);
System.out.println("I recieved valid input: "+validNumber);
}else{
System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
}
line = getLineFromConsole();
}
}
private boolean isValidInput(String line){
//basic sanity
if(null == line || line.length() < 1){
return false;
}
try {
int number = Integer.parseInt(line);
return (number >= 0 && number <= 500);
} catch (NumberFormatException e) {
return false;
}
}
public static void main(String[] args) {
new ScanInfo();
}
public String getLineFromConsole(){
System.out.print("\nEnter Quantity on Hand: ");
return keyboard.nextLine();
}
}
Related
What i want to do is, taking input value in variable only0, and the value must be only 0, if the user inputs value 0, then it must show ("we welcome you") line and if not then repeat the same question
System.out.println(" ****Press 0 to start****");
int only0 = sc.nextInt(); //taking input of the user
if (only0 == 0) {
System.out.println(" We Welcome You :-)");
} else {
System.out.println(" YOU ARE REQUESTED TO PRESS ONLY 0 :-)");
}// if end
I like to assume the user is not always going to enter an integer so I load it as a string and then parse to an int to handle off cases.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
int only0 = 0;
try {
only0 = Integer.valueOf(scan.nextLine());
} catch (NumberFormatException e) {
System.out.println("Only enter an integer! Try again.");
continue;
}
if (only0 == 0) {
System.out.println("We welcome you.");
break;
} else {
System.out.println("You did not enter 0!");
continue;
}
}
scan.close();
}
Unfortunately Java doesn't do that(I suppose you are talking about Goto Statement). However, you can still simulate with recursion without looping statement:
import java.util.Scanner;
public class Test{
Scanner input = new Scanner(System.in);
public static void main(String args[]){
Test run = new Test();
run.ask();
}
private void ask(){
System.out.print("Press 0 to start");
if(input.nextInt()==0){
System.out.println(" We Welcome You :-)");
}
else{
System.out.println(" YOU ARE REQUESTED TO PRESS ONLY 0 :-)");
ask();
}
}
}
In case of invalid input, you need to loop back to prompt the user to enter the value again. One of the best ways to do it is by using a do-while loop as shown below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int only0;
boolean valid;
do {
// Start with assuming that the input will be valid. In case of invalid input,
// assign false to valid which will force the loop to run again
valid = true;
System.out.print("Enter zero: ");
try {
// Use Scanner#nextLine to consume Enter as well
only0 = Integer.parseInt(input.nextLine());
if (only0 == 0) {
System.out.println(" We Welcome You :-)");
} else {
System.out.println(" YOU ARE REQUESTED TO PRESS ONLY 0 :-)");
valid = false;
}
} catch (NumberFormatException e) {
System.out.println("This is not a number.");
valid = false;
}
} while (!valid);
}
}
A sample run:
Enter zero: 1
YOU ARE REQUESTED TO PRESS ONLY 0 :-)
Enter zero: a
This is not a number.
Enter zero: 0
We Welcome You :-)
Is there any way to implement Scanner.hasNextInt() so that it can check not only the i+1 token but the i+2 token? I am looking for a way to check if both inputs are numbers without printing the same error message twice.
Input should be in the form
1 2
and I am trying to alert the user if input is of the form
1 a, a 1, a a, aa aa, 1a 1, etc...
What I wish it would look like: (does not work this way)
int pile1, pile2;
// the second call to reader.hasNextInt() would be verifying pile2 to be int
if (reader.hasNextInt() && reader.hasNextInt())
{
pile1 = reader.nextInt();
pile2 = reader.nextInt();
}
else
{
System.out.println("Your input is malformed. Try again");
}
What I currently have:
int pile1, pile2;
if (reader.hasNextInt())
pile1 = reader.nextInt();
else
{
System.out.println("Your input is malformed. Try again");
return;
}
if (reader.hasNextInt())
pile2 = reader.nextInt();
else
{
System.out.println("Your input is malformed. Try again");
return;
}
You can use
hasNext(String pattern) this method returns true if the next token matches the pattern constructed from the specified string.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
List<Integer> data = new ArrayList<Integer>();
System.out.println("input count of numbers to inputed:\t");
int limit = 0;
if (reader.hasNext("\\d+")) {
reader.nextInt();
} else {
System.out.println("wrong input");
return;
}
System.out.println("please input data:\t");
for (int i = 0; i < limit; i++) {
if (reader.hasNext("\\d+")) {
data.add(reader.nextInt());
} else {
System.out.println("Your input is malformed. Try again");
break;
}
}
reader.close();
}
assumption:Since you need to stop scanning ,one must have predefined limit set or special exit condition from loop.
So it looks like it allows me to input all ints, and when i do a string or anything else it does give me error, but how do I go about making it so its ONLY 1 and/or 2 accept and 3,4,5....(every other number) are not excepted...
Code below
public static void main(String[] args){
System.out.println("Please enter 1 to add or 2 to multiply. "); // ask user to input 1 or 2
Scanner in = new Scanner(System.in);
try {
int add = in.nextInt(); // add for 1
int multiply = in.nextInt(); // multiply for 2
}
catch (Exception e) {
System.out.println("Operation failed. You need to enter 1 or 2.");
}
}
Exceptions here would be overkill IMO. Just using if else clauses would work equally well. Like this:
if(input == 1) {
// add
}
else if(input == 2) {
// multiply
}
else {
System.out.println("Operation failed. You need to enter 1 or 2.");
}
Also if you want the program to keep prompting you can just wrap it in a loop. Here is a small example using a boolean sentinel to keep the loop going. This is one of many ways to implement this task.
public static void main(String[] args) {
System.out.println("Please enter 1 to add or 2 to multiply. "); // ask user to input 1 or 2
Scanner in = new Scanner(System.in);
boolean inputNotValid = true;
while(inputNotValid){
int input = in.nextInt();
if(input == 1) {
inputNotValid = false;
//add
System.out.println("adding");
}
else if(input == 2) {
inputNotValid = false;
//multiply
System.out.println("multiplying");
}
else {
System.out.println("Operation failed. You need to enter 1 or 2. Try again");
}
}
}
Replace:
int add = in.nextInt(); // add for 1
int multiply = in.nextInt(); // multiply for 2
with:
int value = in.nextInt();
if(value == 1) // do add
if(value == 2) // do multiply
// else case = error
The whole program would become:
public static void main(String[] args)
{
System.out.println("Please enter 1 to add or 2 to multiply. ");
Scanner in = new Scanner(System.in);
try
{
int value = in.nextInt();
if (value == 1)
{
System.out.println("add");
// do add
}
else if (value == 2)
{
System.out.println("mult");
// do multiply
}
else
{
// error
System.out.println("Operation failed. You need to enter 1 or 2.");
}
}
catch (Exception e)
{
System.out.println("Read operation failed. This should not happen!");
}
}
The javadoc for nextInt() says:
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
You still can catch the InputMismatchException, the NoSuchElementException and the IllegalStateException, since in.nextInt() can throw them. You could also catch Exception (the only superclass of all three exceptions) instead.
Since Exception is an unchecked Exception, you can also remove the try-catch. Beware though, that an error in the Input will then exit the whole program.
The program takes user input which is supposed to be an integer greater than 0. If the user doesn't do this he is notified of the mistake and is reprompted. Once the correct input is entered, the value is returned. What's the best way to do this? The following code is my try but doesn't work. It seems unnecessarily complex for such an easy task.
System.out.println("Please enter an integer greater than 0:");
Scanner scan = new Scanner(System.in);
int red = -1;
do
{
try
{
red = scan.nextInt();
}catch(InputMismatchException e)
{
System.out.println("Number must be an integer");
scan.nextLine();
if(red < 1)
System.out.println("Number must be more than zero");
else
break;
}
}while(true);
return red;
Sometimes I don't know what to put in my question because I already know the code doesn't work - so if there's something else I should tell please let me know.
The basic concept is running in the right direction, beware though, nextInt won't consume the new line, leaving it within the scanner, meaning you will end up with an infinite loop after the first unsuccessful loop.
Personally, I would simply get the input as a String using nextLine, which will consume the new line, causing the next loop to stop at the statement.
Then I would simply parse the String to an int value using Integer.parseInt
For example...
Scanner scan = new Scanner(System.in);
int red = -1;
do {
System.out.print("Please enter an integer greater than 0:");
String text = scan.nextLine();
if (text != null && !text.isEmpty()) {
try {
red = Integer.parseInt(text);
// This is optional...
if (red < 1) {
System.out.println("Number must be more than zero");
}
} catch (NumberFormatException exp) {
// This is optional...
System.out.println("Not a number, try again...");
}
}
} while (red < 1);
I use this class instead of the Scanner or BufferedReader classes to get user input:
import java.io.*;
public class Input{
private static BufferedReader input=new BufferedReader
(new InputStreamReader(System.in));
public static Double getDouble(String prompt){
Double value;
System.out.print(prompt);
try{
value=Double.parseDouble(Input.input.readLine());
}
catch (Exception error){
// error condition
value=null;
}
return value;
}
public static Integer getInteger(String prompt){
Integer value;
System.out.print(prompt);
try{
value=Integer.parseInt(Input.input.readLine());
}
catch (Exception error){
// error condition
value=null;
}
return value;
}
public static String getString(String prompt){
String string;
System.out.print(prompt);
try{
string=Input.input.readLine();
}
catch (Exception error){
// error condition
string=null;
}
return string;
}
}
Now, to answer your question u can write your code like this:
public class InputTest {
public int checkValue() {
int value;
do {
value = Input.getInteger("Enter a value greater than 0: ");
} while (value <= 0);
return value;
}
}
I don't understand the logic to this. If I run this code and enter a non-int such as the letter f, I get stuck in an infinite loop outputting the two println's and I am not given another chance to input an int to the scanner...it just keeps spitting out words to the console.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);//<<<<<SCANNER HERE
int opponents = 0;
boolean opponentsCreated = false;
while(opponentsCreated == false)
{
try
{
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
if(tempOpponents > 0)
{
opponents = tempOpponents;
opponentsCreated = true;
}
}
catch(InputMismatchException notAValidInt)
{
System.out.println("Not valid - must be a number greater than 0 ");
}
}
}
But if I simply change the Scanner to be declared inside the while loop, all of a sudden the program works as expected:
public static void main(String[] args) {
int opponents = 0;
boolean opponentsCreated = false;
while(opponentsCreated == false)
{
Scanner scan = new Scanner(System.in);//<<<<<SCANNER HERE
try
{
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
if(tempOpponents > 0)
{
opponents = tempOpponents;
opponentsCreated = true;
}
}
catch(InputMismatchException notAValidInt)
{
System.out.println("Not valid - must be a number greater than 0 ");
}
}
}
I honestly just sat here for 2 hours trying to figure out what the heck was wrong with my program only to find out it was a matter of where I declared my Scanner even though in both versions of the code the Scanner was not out of scope. So now I'm really curious why it works this way
Adding on to #HovercraftFullOfEels answer:
The root cause is, the scanner position does not move in case of the said exception. So scanner keeps reating same bad input again and again. Quoting JavaDoc
If the translation is successful, the scanner advances past the input
that matched.
catch(InputMismatchException notAValidInt)
{
scan.reset();
System.out.println("Not valid - must be a number greater than 0 ");
//position is still 0
scan.next(); //position is now 1
}
To visualize:
Input: f______________
Scanner position: ^______________
InputMismatchException ^______________
scan.next() _^_____________
Relevant source (look at the source comment):
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
One possible problem is that you may be leaving the end of line token hanging when an excpetion occurs. If you handle this by making sure to swallow the end of line token when needed, you are likely OK. For example:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);// <<<<<SCANNER HERE
int opponents = 0;
boolean opponentsCreated = false;
while (opponentsCreated == false) {
try {
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
// line below corrected!
scan.nextLine(); // *** this might not be a bad idea either ***
if (tempOpponents > 0) {
opponents = tempOpponents;
opponentsCreated = true;
}
} catch (InputMismatchException notAValidInt) {
System.out.println("Not valid - must be a number greater than 0 ");
scan.nextLine(); // ****** this is what you need here *****
}
}
}
Nice question, by the way!