Entering a Int while variable declared Double and vice versa in Java - 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.

Related

How to loop through until user inputs a valid integer?

I'm new to java and am trying to validate numbers being entered into the console. I want an integer, but I know if a letter is entered for example an error would occur, so I thought I'd use try & catch. This works if try and do it first time round, but I want to loop through until the user inputs a valid integer. Got this working, but when I get a valid number and print out the number I get a list of all attempts.... Hope this makes sense
import java.util.Scanner;
public class ConvertStringInt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i = 0;
System.out.print("Enter a whole number: ");
try {
i = sc.nextInt();
} catch (Exception e){
System.out.println("Error");
main(args);
}
System.out.println(i);
}
}
Here is the output from the console....
Enter a whole number: a
Error
Enter a whole number: d
Error
Enter a whole number: 2.0
Error Enter a whole number: 1
1
0
0
0
Could somebody please explain this?
Thanks in advance
Neil
You are seeing outputs for each input because you call main recursively. If you immediately type a correct int, the flow is this:
main
ask for input -> int
print i (1)
But in your case the input is not an int. This is what happens: you type the first input, it fails. You do not print yet because you first call main again, asking for the next input. Only when you get a correct int you print, and then finish and allow the previous main-execution to finish by printing, which then allows the previous... and so on:
main(args)
ask for input -> a !int
main(args)
ask for input -> d !int
main(args)
ask for input -> 2.0 !int
main(args)
ask for input -> 1 int
print 1 (1)
print 0 (2.0)
print 0 (d)
print 0 (a)
Look at Ravi's answer for a proper way to repeatedly ask for input without using try/catch (which is discouraged).
You could check for integer token in loop
while (!sc.hasNextInt()) // loop until next token is integer
{
// do something or print error
System.out.println(sc.next() +"is not number");
}
i = sc.nextInt();

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 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 to make java expression only recognize numbers [duplicate]

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 ^^

How to use multiple Input Dialogs (New to Java)

I am trying to create a program that asks a user for a sentinel value (a value to enter when they want to end the list). It then asks the user to enter numbers until they re-enter the sentinel value. It then figures out the max number in the list. I'm very new to Java, and whenever I run the program is just asks for the sentinel value then does nothing else (never pops up the second input dialog). I'm sure it's something simple that I'm doing wrong, but I can't figure it out. Thanks for any help.
import java.util.*;
import javax.swing.JOptionPane;
public class HW1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int number;
int max;
int sentinel;
int count=0;
JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel=input.nextInt();
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
max = number;
while (number!=sentinel){
count +=1;
if (number>max)
max=number;
JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" to end.");
number = input.nextInt();
}
if (count!=0){
JOptionPane.showMessageDialog(null, "The max is:" + max);
}
}
}
You are mixing the ways to input data to your program. Let's begin:
Scanner input = new Scanner(System.in);
The line above allows you to catch data in the command line from the keyboard.
JOptionPane.showInputDialog("Please enter a sentinel value: ");
This Option Pane is showing correctly, you put a value and then nothing happens. This is because your program is waiting to input something in the command line
sentinel=input.nextInt();
When your program arrives to the line above, the input.nextInt() stops the program until you put something in the command line.
The correct way should be something like this:
sentinel = Integer.parseInt(JOptionPane.showInputDialog("Please enter a sentinel value: "));
number = Integer.parseInt(JOptionPane.showInputDialog("Please enter numbers. Enter" + sentinel +" value to end."));
And remove:
number = input.nextInt();
sentinel=input.nextInt();
I think the confusion is this:
the JOptionPane opens with an input dialog
when the option pane closes, whatever you put there is ignored
then the code goes to this line sentinel=input.nextInt();
which waits for input from the console (e.g. you need to go back to the console, type the number there and press enter, only then the program will advance, it will block untill you do)
I would change it to something like this:
String sentinelInput = JOptionPane.showInputDialog("Please enter a sentinel value: ");
sentinel= Integer.parseInt(sentinelInput);
(repeat for all places where you expect input)
An alternative solution is
Don't use the JOptionPane, and instead just System.out.println to print the user a request for input (instead of the popup dialog). Then you can and keep the existing input.nextInt() calls to collect it.
Just note that all interaction will be in the console, without any popup dialogs (which I actually prefer in terms of user experience, and also it will be working in non GUI machines such as a linux terminal...)

Categories

Resources