How to make java expression only recognize numbers [duplicate] - java

This question already has answers here:
How to check that a string is parseable to a double? [duplicate]
(6 answers)
Closed 9 years ago.
I am making a program and cannot figure out how to make my scanner input only recognize numbers. Here is what I mean.
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
Distance = keyboard.nextDouble();
What can I put after the distance input in order to allow me to output some sort of message telling the user they didn't enter a number.
I thought maybe starting with something like
if (Distance != double)
System.out.print ("You did not enter a valid character, please enter again."
but that does not work. Any suggestions?

You need to use Scanner#hasNextDouble() method to test, whether there is a double value to read:
// While the next input is not a double value, repeat
while (!keyboard.hasNextDouble()) {
System.out.println("Please enter a valid numeric value");
keyboard.nextLine(); // Move Scanner past the current line
}
double distance = keyboard.nextDouble();
Also, the loop might go infinite, if the user keeps on passing wrong input. You can give him some max number of attempt to get it right, and then throw some exception, or display some message, and then do a System.exit(1);.

You can make this using a try cacth block, somethinh like:
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
Distance = keyboard.nextDouble();
try
{
//you next code, considering a valid number
}catch (NumberFormatException ex)
{
//here u show a message ou another thing
}
Hope it helps ^^

Related

Getting "Exception in thread "main" java.util.InputMismatchException" Followed my guide book to the letter [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
Been looking for about an hour now, do not understand where I'm going wrong.
From what I understand it's Scanner looking for an integer but finding a String instead that is causing the issue?
I'm very new to coding but from what I can make out the issue starts here:
public void inputGrades()
{
Scanner input = new Scanner(System.in);
int grade;
System.out.printf("%s\n%s\n %s\n %s\n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
while( input.hasNext())
{
grade = input.nextInt();
total += grade;
++gradeCounter;
incrementLetterGradeCounter(grade);
}
}
I'm following one of Paul Deitel's books on my college course and I'm completely stumped!
Any help is much appreciated!
You can use Integer.parseInt() to convert the string to integer. But Does your printf statement stops getting input when you press Ctrl+Z?
I found something that might work for you. Follow those steps (code sample below):
Initialize your grade variable to something (usually 0 or 1):
int grade = 0;
Use next() instead of nextInt() so that you can read any input:
String nextInput = input.next();
Parse your input with Integer.parseInt(), converting your input into a number:
grade = Integer.parseInt(nextInput);
If your user types a String, it will throw an exception and end your program. You may surround your grade parsing with an try/catch. In your case, the exception thrown would be a NumberFormatException:
try {
grade = Integer.parseInt(nextInput);
System.out.println(grade);
} catch (NumberFormatException e) {
System.out.println("Mauvais format de nombre, veuillez recommencer");
}
Profit ! Below is your full method.
Scanner input = new Scanner(System.in);
int grade = 0;
System.out.printf("%s\n%s\n %s\n %s\n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
while( input.hasNext())
{
String nextInput = input.next();
try {
grade = Integer.parseInt(nextInput);
System.out.println(grade);
} catch (NumberFormatException e) {
System.out.println("Mauvais format de nombre, veuillez recommencer");
}
}
( Sorry for the poor formatting, I had a rough time with the layout. )
You should use matching has/next methods. Scanner.hasNext() matches Scanner.next(), and Scanner.hasNextInt() matches Scanner.nextInt(). If your input contains a token that is not a valid integer, then hasNextInt() will return false while hasNext() will return true. You can use that to your advantage as shown below.
Also, it's good practice to keep variables to the smallest possible scope; therefore I've moved the declaration of grade to inside the loop.
And finally, for portability, use %n instead of \n in your printf calls.
public void inputGrades()
{
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
while (input.hasNextInt())
{
int grade = input.nextInt();
total += grade;
++gradeCounter;
incrementLetterGradeCounter(grade);
}
if (input.hasNext()) {
System.out.printf(
"Fatal error: the token entered as \"%s\" is not a valid integer.%n",
input.next());
System.exit(1);
}
}
Right, I feel like a completed idiot.
Thank you all for your suggestions and I will take them on board and hopefully utilise them soon in my programming!
As it turns out, following Paul Deitel, he uses the command prompt to run his code and his way of showing an end-of-file indicator is by pressing Ctrl+Z, this had been labelled in one of the presentations as both + z as well as ^Z.
When I have tried to input either of those, that is where the error of a string rather than an integer has come up...
Thank you to those who tried to find me an answer!

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.

Prompt user for input after invalid input [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
So I made a program, and I need to keep prompting for coordinates if the user enters a non-negative, invalid input. Meaning that if the user enters a number above 2 or a letter it should ask him to choose again. The problem that I am running into is that right when I enter a letter, the program terminates and I get InputMisMatchException for the letter, and ArrayOutOfBoundsException for the higher numbers. Is there a way to bypass all those errors and just ask the user to pick again?
So for example:
"Enter the coordinates to place an 'X'. Row then Column."
//enters number > 2 or letter
"Invalid input. Please choose again."
Use a do/while loop:
boolean valid = false;
do {
try {
// "Enter the coordinates to place an 'X'. Row then Column."
// validate input
valid = // final value of validation goes here
} catch (Throwable t) {
// invalid input
} while (!valid)
}

How to check for user input without exiting for error

I need to check the user input and ask for a correct one if the value is not a digit. However when I do this code, the program displays an error message and then crashes- it does not ask the user to give a new input. How can that be fixed? Thank you!
import java.util.Scanner;
import java.lang.Math;
public class CentimeterInch
{
public static void main (String [] args)
{
final int MAX=100, feet=12, meter=100;
final double inch=2.54;
Scanner scan = new Scanner (System.in);
System.out.println ("This program converts distances. ");
System.out.println ("Enter distance and unit (e.g. 37 1 or 100 2):");
double distance=scan.nextDouble();
if (!scan.hasNextDouble())
{
System.out.println ("please enter a numeric value");
distance=scan.nextDouble();
}
int unitType = scan.nextInt();
if (distance<0)
{
System.out.println ("Please enter a non negative distance");
}
....
Just bring the if clause before performing scan.nextDouble().
if (!scan.hasNextDouble())
{
System.out.println ("please enter a numeric value");
scan.nextLine();
distance=scan.nextDouble();
}
double distance=scan.nextDouble();
First make sure that the number to be read is a double value, then read it. You were doing the reverse
What is scan.nextLine() doing here?
Suppose the user enters abc 2. scan.hasNextDouble() checks wether the token to be read next is a double value or not. It's not, so scan.hasNextDouble() evaluates to false and the if clause gets executed. Inside the if clause, you have scan.nextLine(). It simply discards the current input from scan, thus flushing scan. If you don't do so, then scan still contains abc 2 and upon executing distance = scan.nextDouble(), the compiler issues an error.
It's better if you replace if with while. Suppose user gives wrong input. Your program checks the input and finds out that it's not a double value. The if clause if executed and the user is asked to enter a numeric value. What if the user again enters a wrong input. This time, you will get an error. Using a while loop makes your program to keep asking the user for a correct input until he enters a numeric value.

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