Why does my program skip nextDouble() after the exception is caught? [duplicate] - java

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 7 years ago.
I'm trying to figure out why my program is skipping a user input so I can come up with a solution. If I intentionally give it bad input and cause the InputMismatchException to be thrown, it skips the inputDouble = in.nextDouble(); line. Here is what the output looks like:
Please enter floating point value or -1 to stop
15.7
Please enter floating point value or -1 to stop
15.7
Please enter floating point value or -1 to stop
r
Number format is incorrect please try again
Please enter floating point value or -1 to stop
Number format is incorrect please try again
Total is: 31.4
And here is my code
import java.util.InputMismatchException;
import java.util.Scanner;
public class AddingNumbers {
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
double inputDouble = 0;
double total = 0;
int tries = 0;
boolean done = false;
while (!done) {
if (tries < 2) {
try {
System.out.println("Please enter floating point value or -1 to stop");
inputDouble = in.nextDouble();
if (inputDouble != -1) {
total = total + inputDouble;
} else {
System.out.println("Total is: " + total);
done = true;
}
} catch (InputMismatchException exception) {
System.out.println("Number format is incorrect please try again");
tries++;
}
} else {
System.out.println("Total is: " + total);
done = true;
}
}
in.close();
}
}

You could try to put a blank in.nextLine(); right below your inputDouble=in.nextDouble();

The Scanner still has invalid input in the buffer. To "clear" the buffer you need to use in.nextLine();. Use in.nextLine(); after tries++ to solve your problem.

Related

How to loop wrong data type inputs? [duplicate]

This question already has an answer here:
While loop to determine if entered value is a double
(1 answer)
Closed 1 year ago.
I know there are lots of questions similar to this but I can't understand most of it, also I can't see any similar questions related to java language.
So can you guys help me how to loop this question if the input is not a double data type?
The code:
System.out.println("Enter first number");
num1 = input.nextDouble();
System.out.println("Enter second number");
num2 = input.nextDouble();
I really appreciate anyone who tries to answer, tia!!
This is a solution (without exception handling). It loops until two Doubles have been entered. So it is possible to enter this:
3
4.2
or also:
www
3
abc
4.2
Both will give the same result
3
4.2
Note that the code is locale sensitive in regard of the numbers you enter at the command prompt (meaning that the decimal sign depends on your computer settings – in Germany for example it is the comma and not the dot, so you would enter 4,2):
Scanner scanner = new Scanner(System.in);
Double part1 = null;
Double part2 = null;
while (true) {
if (scanner.hasNextDouble()) {
if (part1 == null ) {
part1 = scanner.nextDouble();
} else {
part2 = scanner.nextDouble();
break;
}
} else {
scanner.next(); // The input is not a Double, so just drop it
}
}
scanner.close();
System.out.println(part1);
System.out.println(part2);
If you add the line scanner.useLocale(Locale.ROOT) after creating the scanner:
Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.ROOT);
the decimal sign will be the dot '.' like in 4.2 independent of the settings of your computer.
I like to create a separate method to validate input. If the value is invalid, then I have the method return -1. Then I'll have a while loop that checks if the input is -1, if so, than it'll ask the for a new input value till it's correct. There are many ways to go about it. But the gist is something like this.
public static void main(String[] Args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
double num1 = validateDouble(input);
while (num1 == -1) {
num1 = validateDouble(input);
}
System.out.println(num1);
}
private static double validateDouble(Scanner scanner) {
String input = scanner.nextLine();
try {
double i = Double.parseDouble(input);;
return i;
}catch (InputMismatchException | NumberFormatException e) {
if (input.equals("q")) {
System.exit(0);
}
System.out.println("Please try again.");
return -1;
}
}

Asking for an integer [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I try to solve the next task:
1. Asking the user for a positive integer.
2. If the user adds a negative or a real number or both, the next error message should be displayed on the console: "wrong input".
That is what I have done so far.
Scanner sc = new Scanner(System.in);
System.out.print("Please, add a positive integer! ");
int num = sc.nextInt();
if (num < 0) {
System.out.println("wrong input");
}
Everything works well, except I cannot make sure that the user receives the error message if he/she doesn't type an integer but a real number. In this case, the program goes wrong.
I would appreciate the help.
import java.util.Scanner;
import java.util.InputMismatchException;
public class ScanTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
boolean badInput = true;
int num;
// Keep asking for input in a loop until valid input is received
while(badInput)
{
System.out.print("Please, add a positive integer! ");
try {
num = Integer.parseInt(sc.nextLine());
// the try catch means that nothing below this line will run if the exception is encountered
// control flow will move immediately to the catch block
if (num < 0) {
System.out.println("Please input a positive value.");
} else {
// The input is good, so we can set a flag that allows us to exit the loop
badInput = false;
}
}
catch(InputMismatchException e) {
System.out.println("Please input an integer.");
}
catch(NumberFormatException e) {
System.out.println("Please input an integer.");
}
}
}
}
Occasionally I find it easier to read in a string and then try and parse it. This presumes you would like to repeat the prompt until you get a valid number.
Scanner sc = new Scanner(System.in);
int num = -1;
while (num < 0) {
System.out.print("Please, add a positive integer! ");
String str = sc.nextLine();
try {
num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("Only integers are accepted.");
continue;
}
if (num < 0) {
System.out.println("Input is < 0.");
}
}
Read about NumberFormatException here.
When you're using Scanner.nextInt() the input is expected to be an integer. Inputting anything else, including a real number, will throw an InputMismatchException. To make sure invalid input doesn't stop your program, use a try/catch to handle the exception:
int num;
try {
num = sc.nextInt();
// Continue doing things with num
} catch (InputMismatchException e) {
// Tell the user the error occured
}

Adding message when certain condition is met (Java)

Total newbie here, please forgive the silly question. As an exercise I had to make a program (using do and while loops) that calculates the average of the numbers typed in and exits when the user types 0. I figured the first part out :) The second part of the exercise is to change the program to display an error message if users types 0 before typing any other number. Can you kindly explain to me what is the easiest way to accomplish this? If you provide the code is great but I’d also like an explanation so I am actually understanding what I need to do.
Thank you! Here is the code:
import java.util.Scanner;
public class totalave1 {
public static void main(String[] args) {
int number, average, total = 0, counter = 0;
Scanner fromKeyboard = new Scanner(System.in);
do {
System.out.println("Enter number to calculate the average, or 0 to exit");
number = fromKeyboard.nextInt();
total = total + number;
counter = counter + 1;
average = (total) / counter;
} while (number != 0);
System.out.println("The average of all numbers entered is: " + average);
}
}
The second part of the exercise is to change the program to display
an error message if users types 0 before typing any other number.
It is not very clear :
Do you you need to display a error message and the program stops ?
Do you you need to display a error message and to force the input to start again ?
In the first case, just add a condition after this instruction : number=fromKeyboard.nextInt(); :
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
return;
}
...
} while (number!=0);
In the second case you could pass to the next iteration to take a new input.
To allow to go to next iteration, just change the number from zero to any value different from zero in order that the while condition is true.
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if (number == 0 && counter == 0){
System.out.println("Must not start by zero");
number = 1;
continue;
}
...
} while (number!=0);
The good news is that you probably have done the hardest part. :) However, I don't want to give too much away, so...
Have you learned about control flow? I assume you might have a little bit, as you are using do and while. I would suggest taking a look at the following Java documentation first: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
Then, look at your current solution and try to think what conditions you have that would lead you to display the error message, using if statements. How do you know the user typed a 0? How do you know it's the first thing they entered? Are there any variables that you have now that can help you, or do you need to create a new one?
I know this is not a code answer, but you did well in this first part by yourself already. Let us know if you need further hand.
Don't go down code after reading and if you cant then see the code.
First you have to learn about the flow control. Second you have to check whether user entered 0 after few numbers get entered or not, for that you have to some if condition. If current number if 0 and it is entered before anyother number then you have to leave rest of the code inside loop and continue to next iteration.
import java.util.Scanner;
public class totalave1
{
public static void main (String[]args)
{
int number, average, total=0, counter=0;
boolean firstTime = true;
Scanner fromKeyboard=new Scanner (System.in);
do{
System.out.println("Enter number to calculate the average, or 0 to exit");
number=fromKeyboard.nextInt();
if(firstTime && number==0){
System.out.println("error enter number first");
number = -1;
continue;
}
firstTime = false;
total=total+number;
counter=counter+1;
average=(total)/counter;
} while (number!=0);
System.out.println("The average of all numbers entered is: "+average);
}
}
Here is a simple program that extends on yours but uses nextDouble() instead of nextInt() so that you can enter numbers with decimal points as well. It also prompts the user if they have entered invalid input (something other than a number):
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java_Paws's Average of Numbers Program");
System.out.println("======================================");
System.out.println("Usage: Please enter numbers one per line and enter a 0 to output the average of the numbers:");
double total = 0.0;
int count = 0;
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double inputNum = scanner.nextDouble();
if(inputNum == 0) {
if(count == 0) {
System.out.println("Error: Please enter some numbers first!");
} else {
System.out.println("\nThe average of the entered numbers is: " + (total / count));
break;
}
} else {
total += inputNum;
count++;
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter a number: ");
scanner.next();
}
}
}
}
Try it here!

How to end a while loop [duplicate]

This question already has answers here:
Cant figure out how to exit the loop of my program
(3 answers)
Closed 6 years ago.
My program for class asks to run the program as long as the user doesn't enter the input of -99. When I run the program and enter a usable number that isn't -99, the console will run a continuous looping answer until I have to press end.
How can I change the program so for each input there will be one answer and the program restarts until user inputs -99?
import java.util.Scanner; //import scanner
import java.io.*; //import library
public class is_odd_or_even_number {//begin class
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
//begin testing for odd or even in new method
public static boolean isEven(int num){
return(num & 1) == 0;
}
}
Here, you don't let the user entry other thing that the first input before the loop.
The retrieval of the input from the user :
int number = input.nextInt();
should be in the loop.
Try that :
int number = 0;
//PART I NEED HELP WITH **************
while (number != -99){
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else
System.out.println("Your number is Odd!");
}
}
You can do like this way ;)
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
//PART I NEED HELP WITH **************
while (number != -99){
System.out.print("Not good, please enter a new one : ");
number = input.nextInt();
}
//Start of if statement to test which to print and call of isEven method
if (isEven(number)) {
System.out.println("Your number is Even!");
}
else {
System.out.println("Your number is Odd!");
}
So it will ask until you're not writing -99 as you said, but if you're asking for "a positive int" normally nobofy would write -99 :p
End a while loop
You can use a boolean value shouldContinue to control whether the programs should continue to the next input.
if (number != -99) {
shouldContinue = true;
} else {
shouldContinue = false;
}
This can be simplified as follow:
shouldContinue = number != -99 ? true : false;
// or even shorter
shouldContinue = number != -99;
Read the value correctly
But you need to ensure that you input number is reset at each loop execution so that you can read the next number:
while (shouldContinue) {
...
number = input.nextInt();
}
Other enhancements
Do not import unused packages or classes
Use camel case for Java class name
Use comment style /** ... */ for Javadoc
Always try to avoid infinite loop, e.g. use an integer count tries and count down at each loop.
Here's the final answer look like:
import java.util.Scanner;
public class IsOddOrEvenNumber {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
boolean shouldContinue = true;
int tries = 0;
while (shouldContinue && tries < 10) {
try {
System.out.print("Enter a positive integer value: ");
int number = input.nextInt();
if (isEven(number)) {
System.out.println("Your number is Even!");
} else {
System.out.println("Your number is Odd!");
}
shouldContinue = number != -99 ? true : false;
} catch (Exception notNumber) {
System.out.println("Input not a number, try again.");
}
tries--;
}
System.out.println("Game over.");
}
/**
* Begin testing for odd or even in new method
*/
public static boolean isEven(int num){
return (num & 1) == 0;
}
}
Here you are the main method which will be running as long as user is not entering -99;
You should include all your code in the while loop (even try/catch).
public static void main(String []args) {//begin main
Scanner input = new Scanner(System.in);
int number = 0;
//Keep application running as long as the input is not -99
while (number != -99){
//use try/catch method to test for invalid input
try{
//promt user to input a value
System.out.print("Enter a positive integer value: ");
number = input.nextInt();
//Start of if statement to test which to print and call of isEven method
//if the entered number is -99, the following code will skipped.
if(number == -99) continue;
if (isEven(number))
System.out.println("Your number is Even!");
else
System.out.println("Your number is Odd!");
}
//open catch method and print invalid
catch(Exception notNumber) {
System.out.println("Input not a number, try again.");
}
}
}
You could accept this answer, in case it is what you are looking for :)

Exception Handling works only once in running program

Initially I tried to put the try statement into the while loop, however, I was encountered with several errors. The program runs perfectly except when I input a irregular character once it gives me the Printed line I inputted I created, however, when I inputted another one again, the line does not pop up and rather gives me a format exception error.
AddNumbersrealone2.java
import java.io.*;
// create the class
public class AddNumbersrealone2
{
// allows i/o
public static void main (String [] args) throws IOException
{ // initalize variables and strings
BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
String sumNumbers;
//String go;
double num ;
double total = 0.0;
// asks user questions and instructions
System.out.println("Hello, the following program will ask for your input of a number ");
System.out.println("Each time you input a number a running total will be added to each previous number") ;
System.out.println("Once ready input a number to start!");
// try and catch block
try {
num = 0;
// while statement if this occurs stop the program, in this case if a negative integer is inputted
while (num >= 0) {
// Contious question asked
System.out.println("Input another number...");
sumNumbers = myInput.readLine();
num = Double.parseDouble (sumNumbers);
// calculates number (Running total)
total = total + num;
System.out.println(total);
// end error trap
}
}
catch (Exception e){
System.out.println("Please refrain from entering regular characters!");
num = 0;
// re- while statement if this occurs stop the program, in this case if a negative integer is inputted
while ( num >= 0) {
// input question after a character is inputted
System.out.println("Please input a number: ");
sumNumbers = myInput.readLine();
num = Double.parseDouble (sumNumbers);
total = total + num;
System.out.println(total);
// ending statement
}
}
System.out.println("You entered a negative number, the program will exit now");
System.out.println("Good-bye!");
// Complete class body
}
}
You want something to catch the exception around the Double.parseDouble
for example.
while(num >= 0)
{
// input question after a character is inputted
System.out.println("Please input a number: ");
sumNumbers = myInput.readLine();
try{
num = Double.parseDouble (sumNumbers);
total = total + num;
System.out.println(total);
} catch(Exception e)
{
System.out.println("Please enter a proper number");
}
// ending statement
}
Your problem is that as soon as the first exception is thrown, your program becomes caught up inside the while() loop inside of your catch statement. Thus, if another invalid input is entered, it is dealt with in that second while loop where you have no try-catch statement. A good fix would be to have your try statement encompass only the line where you say num = Double.parseDouble (sumNumbers);. When you catch the exception, end it with a continue; statement so that your program loops back the beginning and asks for another input.

Categories