I am VERY new to Java, I am trying to do a unit conversion program from Fahrenheit to Celsius and I am stun on the validation loop. This is what I got.
// Validation
do {
isNumber = true;
System.out.print("What is the temperature in Fahrenheit?: ");
// If alphabetical characters are entered
while (!input.hasNextDouble()) {
System.out.println("Oops! Try entering only numerical characters.");
System.out.println();
isNumber = false;
input.next();
}
fahrenheit = input.nextDouble();
} while (!isNumber);
as you can see what I am trying to validate is that the user doesn't enter a string. but when I run the program it gets stuck on some sort of loop and it says
What is the temperature in Fahrenheit?: something <-- what I input
Oops! Try entering only numerical characters.
and that's it. it doesn't go back to the the input or anything, it just stays there until I enter a number and then it goes back to
What is the temperature in Fahrenheit?:
To clarify, my problem is only with the validation loop, because when I enter a number it works just fine. The problem ONLY appears when I enter a string.
Example code:
import java.util.Scanner;
public class QuickTester {
public static void main(String[] args) {
double fahrenheit;
Scanner input = new Scanner(System.in);
// Validation
while(true) {
System.out.print("What is the temperature in Fahrenheit?: ");
// If alphabetical characters are entered
if (!input.hasNextDouble()) {
System.out.println("Oops! " +
"Try entering only numerical characters.\n");
// Clear away erroneous input
input.nextLine();
}
else {
fahrenheit = input.nextDouble();
break; // Get out of while loop
}
}
input.close();
System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}
}
Input/Output:
What is the temperature in Fahrenheit?: abc
Oops! Try entering only numerical characters.
What is the temperature in Fahrenheit?: banana
Oops! Try entering only numerical characters.
What is the temperature in Fahrenheit?: 36.5
Temperature in Fahrenheit: 36.5
Note:
Revised the code. You do not need a while loop within a do-while loop.
Check if the input is a double, break out of while loop if it is indeed a double value.
Something like this will do
Scanner input = new Scanner(System.in);
double fahrenheit;
do {
System.out.print("What is the temperature in Fahrenheit?: ");
try {
fahrenheit = input.nextDouble();
//Do your work
break;
} catch (InputMismatchException ex) {
input.nextLine();
System.out.println("Oops! Try entering only numerical characters.");
System.out.println();
}
} while (true);
this will do the trick.
public class Main
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
System.out.print( "What is the temperature in Fahrenheit?: " );
// If alphabetical characters are entered
while ( !input.hasNextDouble() )
{
System.out.println( "Oops! Try entering only numerical characters." );
System.out.println();
input.next();
}
//Do Fahrenheit to Celsius calculation
}
}
Related
The following code will give me what I want which is the type of data entered (int, double, or string) however, when I run the code it is as if it expects another input before it will execute. I hope I'm on the right path.
or
Enter some stuff: 43
3
You have entered an integer: 43
It will not run until I enter another character in this case the 3 below 43.
Thanks for looking.
public static void main(String[] args)
{
// variables
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
if (in.hasNextInt())
{
System.out.print ("You have entered an integer: "+ input);
}
else if (in.hasNextDouble())
{
System.out.print ("You have entered a double: "+ input);
}
else if (in.hasNextLine())
{
System.out.print ("You have entered a string: "+ input);
}
}
I would use try and catch in order to found the right data type. Don't use multiple inputs otherwise you will get the error that you got, just use in.next() once and then handle the value as below:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
input = in.next();
//determine and read type echo to use
try {
int v = Integer.parseInt(input);
System.out.print ("You have entered an integer: " + input);
} catch (NumberFormatException nfe1) {
try {
double v = Double.parseDouble(input);
System.out.print ("You have entered a double: " + input);
} catch (NumberFormatException nfe2) {
System.out.print ("You have entered a string: " + input);
}
}
}
Output 1:
Enter some stuff: 7
You have entered an integer: 7
Output 2:
Enter some stuff: 3.0
You have entered a double: 3.0
Output 3:
Enter some stuff: sfsdfasd
You have entered a string: sfsdfasd
I think you are doing it incorrectly. If you want to know the type of the data you entered, why would you read it first? You are first reading and storing it in input variable and determining the type of the next entered input. So, the message is also wrong. I've altered your code to get desired output
public static void main(String[] args) {
// variables
Scanner in = new Scanner(System.in);
String input;
// Prompt user for stuff
System.out.print ("Enter some stuff: ");
// input stuff
// input = in.next();
//determine and read type echo to use
if (in.hasNextInt())
{
System.out.println ("You have entered an integer: "+ in.nextInt());
}
else if (in.hasNextDouble())
{
System.out.println ("You have entered a double: "+ in.nextDouble());
}
else if (in.hasNextLine())
{
System.out.println ("You have entered a string: "+ in.nextLine());
}
}
THis is a part of my input
I would like the user to input only in float, what does this mean?:
Boolean start;
do{
System.out.println("Enter value for Alpha:");
if(sc.hasNextFloat()){
al = sc.nextFloat();
start = true;
} else{
System.out.println("Please enter a number");
start = false;
sc.next();
}
} while(!(start));
You can use following code for your problem:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for Alpha:");
while(true) {
if(sc.hasNextFloat()) {
float al = sc.nextFloat();
System.out.println(al);
break;
} else {
System.out.println("Enter a valid float");
sc.next();
}
}
sc.close();
}
boolean start;
start = false;
Scanner sc = new Scanner(System.in);
float alphaFloat;
do {
try{
System.out.println("Enter value for Alpha: ");
String alpha = sc.next();
if(alpha.contains(".")) {
System.out.println("Float stored");
alphaFloat = Float.valueOf(alpha);
start = true;
}
else {
System.out.println("Please enter a float. That was not a float.");
}
catch(NumberFormatException e) {
System.out.println("Please enter a number that is properly formatted");
}
finally {
System.out.println("\r\n");
}
}while(!start);
Here is your sample output:
Enter value for Alpha:
2.2.2.2
Invalid
Enter value for Alpha:
2
Please enter a float. That was not a float.
Enter value for Alpha:
3.5
Float stored
In your code the user could enter an int technically and it will still execute although you have the hasNextFloat() method within your conditional statement. I edited the code and made the input a String. Therefore, if the String has a decimal within it, we can typecast it to a float. If there is no decimal, We know that it is not a float and will ask for additional input. Now, another factor is that you could typecast any user input to a float if you wanted to. It would probably also be a good idea to set up a try-catch block so that you can handle a user potentially entering an invalid number.
boolean loop = false;
double numberOfStudents;
System.out.print("Enter a number: ");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
while (loop) {
System.out.println("Enter a number");
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
I'm trying to get the program to say "Enter a number" until the user has entered an actual number (no white spaces or letters or signs). When the user has entered a number, it sets numberOfStudents equal to that number and breaks out of the loop.
But if you hit enter twice, it doesn't iterate. It only displays "Enter a number" once.
What is wrong with the loop logic? Why isn't it looping until valid input is taken?
For the actual answer to your question of "Why doesn't 'Enter a number' display more than once?" see Tom's comment (update: Tom's answer).
I've rewritten your loop in a way which preserves your code, but also makes it a little easier to handle format exceptions (though at the risk of silently swallowing an exception -- should be acceptable for this use case).
Can be up to you to use this design, here is an SO post on why empty catch blocks can be a bad practice.
public static void main(String args[])
{
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(loop){
System.out.print("Enter a number: ");
String input = scnr.nextLine();
try{
numberOfStudents = Double.parseDouble(input);
loop = false;
}catch(NumberFormatException e){
}
}
System.out.println("You're outside the loop!");
}
Output:
Enter a number:
Enter a number:
Enter a number:
Enter a number: 50
You're outside the loop!
First of all: Since you're reading from System.in a call to the input stream will block until the user entered a valid token.
So let's check first scan using your scnr variable:
scnr.nextLine()
nextLine() reads everything til the next line delimiter. So if you just press return, then it will successfully read it and will perform the next stuff.
The next call is:
scnr.hasNextDouble()
This call expects a "real" token and ignores white spaces, except as a delimiter between tokens. So if you just press return again it doesn't actually read that input. So it still waits for more (for the first token). That is why it stucks in your loop and you won't get another "Enter a number" output.
You can fix that by either enter a real token, like a number, or by changing the loop like trobbins said.
I hope you now understand your program flow a bit more :).
While trobbins code basically solves your problem, it's bad practice to use exceptions for flow control.
I used a small regexp to check if the value is a number. But this example is not complete, it will still crash it the user enters for example two decimal points. So you would need to create a proper number check or just use integers where the check is much easier.
Someone in the comments pointed out that people may want to enter scientific notation like 5e10, so this would also be another case to check for. If this is just some code you need as a proof of concept or something quick and dirty, you can go with the exception handling method but in production code you should avoid using exceptions this way.
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
while(true) {
System.out.print("Enter a number: ");
String input = scnr.nextLine().trim();
if(input.matches("^[0-9\\.]{1,}$")) {
System.out.println("Loop has stopped");
numberOfStudents = Double.parseDouble(input);
break;
}
}
System.out.println("You're outside the loop!");
The following code should help you:
double numberOfStudents = 0;
Scanner scnr = new Scanner(System.in);
boolean readValue = false; //Check if the valid input is received
boolean shouldAskForNumber = true; //Need to ask for number again? Case for Enter
do {
if (shouldAskForNumber) {
System.out.print("Enter a number:");
shouldAskForNumber = false;
}
if (scnr.hasNextDouble()) {
numberOfStudents = scnr.nextDouble();
readValue = true;
} else {
String token = scnr.next();
if (!"".equals(token.trim())) { //Check for Enter or space
shouldAskForNumber = true;
}
}
} while (!readValue);
System.out.printf("Value read is %.0f\n", numberOfStudents);
System.out.println("You're outside the loop!");
Update
Understood the following statement in question different way:
But if you hit enter twice, it doesn't loop back. It only displays
"Enter a number" once.
The code is set to print "Enter a number" only once if the user hits RETURN/ENTER or enters space character. You may remove the special check and use the code if needed.
import java.util.Scanner;
public class Testing {
public static boolean checkInt(String s)
{
try
{
Integer.parseInt(s);
return true;
} catch (NumberFormatException ex)
{
return false;
}
}
public static void main(String[] args) {
boolean loop = false;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
String input = "";
while (!(checkInt(input))) {
System.out.println("Enter a number");
input = scnr.nextLine();
}
numberOfStudents = Integer.parseInt(input);
System.out.println("Number of students: " + numberOfStudents );
}
}
//this code is working fine, if you want you check it out.
//In your code your taking another input if the first is an int/double; if the first input is not a number then you have mentioned to take input again..
Use a debugger to see what the code is actually doing. Here's a guide on debugging in Eclipse. After you have finished debugging your code, you will probably know what the problem is.
Below code will help you
boolean loop = true;
double numberOfStudents;
Scanner scnr = new Scanner(System.in);
System.out.print("Enter a number: ");
String input = scnr.nextLine();
while(!scnr.hasNextDouble()){
System.out.print("Enter a number: ");
try{
numberOfStudents = Double.parseDouble(input);
break;
}catch(NumberFormatException e){
}
input = scnr.nextLine();
}
System.out.println("You're outside the loop!");
The following code is working,
boolean loop = true;
double numberOfStudents;
Scanner scnr=new Scanner(System.in);
while(loop) {
System.out.println("Enter a number");
if ((scnr.nextLine().trim().isEmpty()) ) {
loop = true;
}
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
System.out.println("You're outside the loop!");
The output is,
run:
Enter a number
hj
po
Enter a number
lhf
Enter a number
o
Enter a number
p
Enter a number
a
Enter a number
34
Loop has stopped
You're outside the loop!
You have to scan the next line if you want to get more values form the scanner again. The code should be like:
while (loop) {
System.out.println("Enter a number");
if(!(scnr.nextLine().trim().isEmpty())){
if (scnr.hasNextDouble() ){
System.out.println("Loop has stopped");
numberOfStudents = scnr.nextDouble();
loop = false;
}
}
}
I am having trouble with entering non-integers into an integer field. I am only taking precautions so that if another person uses/works on my program they don't get this InputMismatchException.
When I enter a non-digit character into the input variable, I get the above error. Is there any way to compensate for this like one could do for a NullPointerException when it comes to strings?
This code is redacted just to include the relevant portions causing the problem.
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
input = user_input.nextInt();
System.out.println("You are: " +input+ " years old");
}
}
You can use an if statement to check if user_input hasNextInt(). If the input is an integer, then set input equal to user_input.nextInt(). Otherwise, display a message stating that the input is invalid. This should prevent exceptions.
System.out.println("What is your age? : ");
if(user_input.hasNextInt()) {
input = user_input.nextInt();
}
else {
System.out.println("That is not an integer.");
}
Here is some more information about hasNextInt() from Javadocs.
On a side note, variable names in Java should follow the lowerMixedCase convention. For example, user_input should be changed to userInput.
You can add a try-catch block:
import java.util.Scanner;
class MyWorld {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int input = 0;
System.out.println("What is your age? : ");
try{
input = user_input.nextInt();
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
}
System.out.println("You are: " +input+ " years old");
}
}
If you want to provide the user to enter another int you can create a boolean variable and make a do-while loop to repeat it. As follows:
boolean end = false;
//code
do
{
try{
input = user_input.nextInt();
end = true;
}catch(InputMisMatchException ex)
System.out.println("An error ocurred");
end = false;
System.out.println("Try again");
input.nextLine();
}
}while(end == false);
This is a try-catch block. You need to use this if you want to be sure of not making the program-flow stop.
try {
input = user_input.nextInt();
}
catch (InputMismatchException exception) { //here you can catch that exception, so program will not stop
System.out.println("Integers only, please."); //this is a comment
scanner.nextLine(); //gives a possibility to try giving an input again
}
Test using hasNextInt().
Scanner user_input = new Scanner(System.in);
System.out.println("What is your age?");
if (user_input.hasNextInt()) {
int input = user_input.nextInt();
System.out.println("You are " + input + " years old");
} else {
System.out.println("You are a baby");
}
Use Scanner's next() method to get data instead of using nextInt(). Then parse it to integer using int input = Integer.parseInt(inputString);
parseInt() method throws NumberFormatException if it is not int, which you can handle accordingly.
In school I had to make a calculator program. In the program, we ask the user if they want to add, subtract, multiply, or divide. At the end, we ask the user of they want to continue the program or no. I haven't put in the looping part yet, but my problem here is that after the "Would you like to continue" is displayed, the program just exits.
package calculator;
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
{
int o1; //first operand
int o2; //second operand
Scanner input = new Scanner (System.in);
System.out.println("Enter a choice:");
System.out.println("+ to add");
System.out.println("- to subtract");
System.out.println("* to multiply");
System.out.println("/ to divide");
System.out.println("X to exit");
String userChoice = input.nextLine();
if (userChoice.equals("X to exit")) {
System.exit(0);
}
System.out.println("Enter the first operand:");
o1 = input.nextInt();
System.out.println("Enter the second operand:");
o2 = input.nextInt();
if (userChoice.equals("+ to add")) {
System.out.println( (o1) + (o2) ); }
else if (userChoice.equals("- to subtract")) {
System.out.println( (o1) - (o2) ); }
else if (userChoice.equals("* to multiply")) {
System.out.println( (o1) * (o2) ); }
else if (userChoice.equals("/ to divide")) {
System.out.println( (o1) / (o2) ); }
System.out.println("Would you like to continue?");
System.out.println("Yes");
System.out.println("No");
String userPick = input.nextLine(); {
if (userPick.equals("Yes")) {
System.out.println("Ok."); }
else if (userPick.equals("No")) {
System.exit(0); }
}
}
}
// TODO Auto-generated method stub
}
Try this:
Scanner input = new Scanner (System.in);
while(true){
System.out.println("Enter a choice:");
System.out.println("+ to add");
......
if (userPick.equals("Yes")) {
System.out.println("Ok."); }
else if (userPick.equals("No")) {
System.exit(0); }
}
}
It will continue to loop around the logic until the terminating condition is met. You may also like to close the scanner before System.exit(); and before any termination in fact.
System.out.println("Would you like to continue?");
System.out.println("Yes");
System.out.println("No");
// add this lline, it can make a difference
input.nextLine();
String userPick = input.nextLine();
You need a while(true) {} loop at the place in the program where you want it to restart. This way, you can go back to the beginning if the user says yes, but the program will exit if the user says no.
You can add a line before your code
String userPick = input.nextLine(); which line is input.nextLine();
it can work well, which can receive enter break line.you can try.
ps:my english is bad,I am not sure I expressed clearly.