Force user to enter a valid number using the Java scanner - java

I have a simple code that asks for the age of a user. Everything is working as it should, except, if I type nothing and simply press enter I enter into something - maybe infinite loop? I am not sure but I cannot get out of it.
I have seen countless questions and responses for this topic when dealing with strings but barely any with byte (or int).
This is my code:
//App #2: Age
System.out.print("Enter your Age: ");
byte age = scanner.nextByte();
while (!scanner.hasNext()) {
System.out.println("Please enter a valid number.");
byte test = scanner.nextByte();
}
if (age > 16) {
applicant.age = age;
System.out.println(age);
}
else
System.out.println("You must be at least 17 years old to obtain a microloan.");
What can I do to force a user to enter a valid number?

Your loop needs to continue as long as additional input is available (i.e., scanner.hasNext()) but it isn't a valid byte (i.e., !scanner.hashNextByte()). You should also remember to consume (next()) any invalid string so the next inputed string can be evaluated:
while (scanner.hasNext() && !scanner.hasNextByte()) {
System.out.println("Please enter a valid number.");
scanner.next(); // Discard the invalid string
}
// Now we have a valid byte, read it:
byte age = scanner.nextByte();

Related

How can i fix this Integer variable to String?

I have a integer variable but I want it so that
if the user inputs the string 'quit' it will close the program.
public static void input() {
System.out.println("Input: ");
Integer choice = scan.nextInt();
choiceExecute(choice);
if (choice == 'quit') {
goBack();
}
}
Thanks in advance.
Use scan.hasNextInt() to check if the input is a Integer. If so, you can use scan.nextInt(); for getting the integer. If it returns false, you can read the value with scan.nextLine(). If this equals quit, the program should close.
There are a couple things wrong here.
This only searches for Integers:
Integer choice = scan.nextInt();
However, this will return the entire line:
String line = scan.nextLine();
And from this you can do the check to see if it is equal to quit:
if(line.equals("quit"){
// do your processing
goBack();
}else{
Integer num = Integer.parseInt(line);
// do your processing on the number
choiceExecute(num);
}
This is of course making the assumption that you are only storing one item per line and that all other lines that are not equal to "quit" are indeed numbers. Here is how I assume your data looks:
221
357
quit
43
565
quit
One way would be to just read in strings using:
scan.nextLine();
(So you can easily check for "quit").
Then just covert the string to an Integer using:
Integer.parseInt(myString);

Entering a Int while variable declared Double and vice versa in Java

Please help.
Statement needs to print:
"Please enter the insured value of your home as a whole number: "
Which is simple but if I enter a double the another statement prints that reads: "You must only enter an integer: "
That is where I'm stuck. Any way I do it I get fatal logic errors.
Here is my code starting with declared variable and skipping the in between code:
double homeInsVal = 0.0;
<other code>
System.out.printf("%nPlease enter the insured value of your home as a whole number: ");
homeInsVal = input.nextDouble();
{
if (homeInsVal >= 0.0)
{
System.out.printf("%nYou must only enter an integer: ");
homeInsVal = input.nextInt();
}
}
My logic is completely off. The reason why I declare homeInsVal as a double is because if I declare it as a Int as soon as I enter a decimal to purposely prompt the second statement I get a logic error an my code terminates but the way I currently have the code written the second prompt will print even if I enter an integer.
Please help!
Note: This is an intro Java class and while beggars can't be choosers have please explain as simple as possible. Thanks!
Not very clear as to what is the question. If you would want to check if the entered value is an integer or a Double, you can refer the below posts
How to find out if the value contained in a string is double or not
How to check if a double value has no decimal part
You want an integer, but the user can enter what they like, including letters and other rubbish. But you can be sure the user enters something, ie a String. Also, to send the data to your program, the user will press Enter, which puts newline char(S) into the buffer.
What does this all mean? It means you need something like this:
String line = input.nextLine();
try {
Integer number = Integer.parseInt(line);
} catch (NumberFormatException e) {
// input wasn't a number
}
This isn't the whole story, but hopefully you can build on it.

Java: Try to Understand Getting Inputs from Users Using Scanner

I have this programs and a few questions regarding to how .next(), .nextInt(), .hasNext() and .hasNextInt() of Scanner class work. Thank you in advance for any of your help :)
import java.util.Scanner;
public class test {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
int age;
System.out.print("Please enter your age: ");
while (!console.hasNextInt()) {
System.out.print("Please re-enter your age: ");
console.next();
}
age = console.nextInt();
System.out.println("Your age is "+age);
}
}
1/ When !console.hasNextInt() is executed for the first time, why does it ask for an input?
I thought at first the console is empty, so !console.hasNextInt() is True (empty is not an int), then it should go directly from "Please enter your age: " to "Please re-enter your age: " but my thought seems to be wrong.
Here, the user needs to enter something before "Please re-enter your age: " is printed.
2/ The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
3/ For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
The java.util.Scanner.hasNextInt() method returns true if the next
token in this scanner's input can be interpreted as an int value in
the default radix using the nextInt() method.
When you start with a non integer input, hasNextInt() will be false and you will enter while loop. Then it will prompt you to re-enter your age. But if you start with integer, you won't enter the loop. Your age will be printed.
console.next() means it takes next input token and returns String. If you write down your code as:
String s = null;
while (!console.hasNextInt()) {
s = console.next();
System.out.println("You entered an invalid input: " + s);
System.out.print("Please re-enter your age: ");
}
console.next() is being used for handling the non-integer inputs. Now, if you enter a non-integer input twenty, you'll see that console.hasNextInt() will be false and console.next() will read it.
hasNextInt() waits for an input string and then tells you if can be converted to an int. With that in mind, let's go over your questions:
When !console.hasNextInt() is executed for the first time, why does it ask for an input?
Because it blocks until there's some input from the console.
The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
Because hasNextInt() returns true when the input can be converted to an int, for example "21".
For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
Calling next() doesn't wait for a new input, it just swallows the input that was tested by hasNextInt() so the scanner can move on to the next one. It could have been the first statement in the loop, with the same effect.

How to check if a double value contains special characters

I was writing a code for a program in which the user enters 2 to 4 numbers which can be up to 2 decimal places long. However before the user enters these numbers they must enter the pound symbol, e.g. #12.34. I was wondering how i would check if the double value entered began with the pound sign, and if the user forgot to input it, to re-prompt them to do it again. So far im using a String value and the '.startsWith()' code, but I'm finding later on that a String value is making the rest of the program impossible to code, so i was wanting to keep it a double value. This is the code I have at the moment but wish to change to a double:
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
I was wanting to replace the String with double as mentioned previously.
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
// if your excution reaches here. then it means the values entered by user is starting from '#'.
String temp = input;
double value = Double.parseDouble(temp.replace("#",""));
For the rest of the program use value. I think the coding should be possible now.
A double value doesn't have a currency symbol. You should check for the currency symbol as you are doing and remove it before parsing the double.
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("£")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}
doulble number = Double.parseDouble(input.substring(1));
You should use the startsWith method. I don't know why you say that
I'm finding later on that a String value is making the rest of the program impossible to code
Basically, you want to prompt it repeatedly until the user enters the # sign. So why not use a while loop?
System.out.println("Enter a number:");
String s = keyboard.next();
double d = 0.0; // You actually wnat to store the user input in a
// variable, right?
while (!s.trim().startWith("#")) {
System.out.println("You did not enter the number in the correct format. Try again.");
s = keyboard.next();
try {
d = Double.parseDouble(s.substring(1));
} catch (NumberFormatException ex) {
continue;
} catch (IndexOutOfBoundsException ex) {
continue;
}
}
That's a lot of code!
Explanation:
First, it prompts the user to enter a number and store the input in s. That's easy to understand. Now here comes the hard part. We want to loop until the user enters the input with the correct format. Let's see what kind of invalid inputs are there:
The user does not enter a # sign
The user does not enter a number
The first one is handled by the startsWith method. If the input does not start with #, ask the user again. Before that, trim is first called to trim off whitespace in the input so that input like " #5.90" are valid. The second is handled by this part:
try {
d = Double.parseDouble(s.substring(1));
} catch (NumberFormatException ex) {
continue;
} catch (IndexOutOfBoundsException ex) {
continue;
}
If the input is in a wrong format, ask the user again. If the user enters a string with a length less than 1, ask the user again.
"But wait! Why is there a call to the substring method?" you asked. If the user does enter a # in the front, followed by a correct number format, how would you convert that string to a double? Here I just kind of trim the first character off by calling substring.
You could try something like this which removes all character that's not a number or a point:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
System.out.println("Input a number: ");
while (!(input = br.readLine()).equals("quit")) {
Double parsedDouble;
if (input.matches("#[0-9]+\\.[0-9]{1,2}")) {
parsedDouble = Double.parseDouble(input.replaceAll("[^0-9.]+", ""));
System.out.println("double: " + parsedDouble);
System.out.println("Input another number: ");
} else {
System.out.println("Invalid. Try again. Example: #10.10");
}
}
}

How can I create an exception that checks for int range, number type, and not a char?

I'm trying to wrap my head around exceptions and the problem I'm running into is that I'm being required to create a program that asks for user input for a number 9-99. This number must be error-checked using 3 different exceptions.
e1: number is outside of the range (200)
e2: number is of a data type other than integer (double)
e3: input is another data type other than number (char)
I have tried to create patterns in my if structure to make all three work, however I can't get it to differentiate between e2 and e3. It will always default to e2. This is what I have with only two exceptions, but I would greatly appreciate help with figuring out how to implement the third. Thank you.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean tryAgain = true;
do {
try {
System.out.println("Please enter an integer between 9 and 99: ");
int inInt = input.nextInt();
if (inInt >= 9 && inInt <= 99){
System.out.println("Thank you. Initialization completed.");
tryAgain = false;
}
else if (inInt < 9 || inInt > 99){
throw new NumberFormatException("Integer is out of range.");
}
}
catch (NumberFormatException e1) { // Range check
System.out.println("* The number you entered is not between 9 and 99. Try again.");
System.out.println();
input.nextLine();
}
catch (InputMismatchException e2) { // Something other than a number
System.out.println("* You did not enter an integer. Try again.");
System.out.println();
input.nextLine();
}
} while(tryAgain);
}
}
Here is the output I get right now:
Please enter an integer between 9 and 99:
2
The number you entered is not between 9 and 99. Try again.
Please enter an integer between 9 and 99:
f
You did not enter an integer. Try again.
Please enter an integer between 9 and 99:
88
Thank you. Initialization completed.
https://www.ideone.com/ZiOpGH
In catch (InputMismatchException e2), test to see if input.hasNextDouble() (or input.hasNextFloat() ? Not sure which one is more general...) is true. If it is, then you can distinguish between the case 'user entered a double' and 'user entered a non numeric type'
If you've got to detect three circumstances, you need to have three sets of logic.
Check if the entered characters are a valid numeric value.
Check that the entered number is an integer.
Check that the entered number falls between the low and high bounds.
And you pretty much have to check them in that order.
Scanner conveniently has the hasXXX methods to see whether the characters about to be read match a given pattern.

Categories

Resources