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.
Related
I wrote a program that accepts numbers from the user, and if the user entered, for example, a string instead of a number, then I recursively call the function for the user to enter a number, but in my example, the program throws a StackOverflowException error. If you know what the problem is, please write.
Code:
private static void inputMethod() {
try {
System.err.print("Enter a range from ");
c = input.nextInt();
System.err.print("Enter a range to ");
d = input.nextInt();
if(c > d) {
System.err.println("Invalid Range Entry");
inputMethod();
return;
}
System.err.print("Enter the sum of digits ");
q = input.nextInt();
findNaturalNumbers();
} catch(InputMismatchException e) {
inputMethod();
}
}
The problem is that when InputMismatchExcpetion is thrown, the garbage input that caused the error is still waiting to be read again by the next scanner call. That's so you could potentially go back and try to read it again with next() or nextLine().
The cure is to "flush the toilet", so to speak, by calling either next() or nextLine() in your InputMismatchException handler:
boolean inputWasGood = false;
while (!inputWasGood){
try {
System.out.println("Enter a number: ");
c = input.nextInt();
inputWasGood = true;
} catch (InputMismatchException ex) {
input.nextLine(); // FLUSH AWAY THE GARBAGE!!
System.out.println("Please don't enter garbage!");
}
}
// FINALLY! We got some good input...
If you enter a letter instead of a number the input.nextInt() method throws an exception, but the cursor position in the input stream scanner is not advanced, it's still pointing to the letter. In the exception handler you call inputMethod() again, and because the cursor position is the same the input.nextInt() will again throw an exception, which will cause another call of inputMethod() and so on until the stack is blown up. What you should do is to use a hasNextInt() method to check if the next token on the stream is a correctly formatted integer and if so - read it with nextInt(). To simplify the process you can try to create an additional method which will prompt the user and ask for the input until the correct input is provided:
private int readInt(Scanner scanner, String prompt) {
while (true) {
System.out.println(prompt);
if (scanner.hasNextInt()) {
return scanner.nextInt();
}
System.out.println("Incorrect format of an integer number");
scanner.nextLine();
}
}
and then you can use it like this:
do {
c = readInt(input, "Enter a range from ");
d = readInt(input, "Enter a range to ");
if(c > d) {
System.err.println("Invalid Range Entry");
}
} while (c > d);
q = readInt(input, "Enter the sum of digits ");
findNaturalNumbers();
I'm trying to ask the user for a number and if they enter anything wrong (not an int between 1 and 99) then catch (to prevent crash if string) and loop until enter a right number. My loop is stuck in an endless loop somehow. Note: I do have the Scanner imported and the exception imported too.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String result;
int number;
boolean done = false;
while (true) {
try {
System.out.println("Please select a number from 1 to 99.");
number = input.nextInt();
input.nextLine();
if (number >= 1 || number <= 99) {
result = checkNumber(number);
System.out.println(result);
break;
}
} catch (InputMismatchException exception) {
}
}
}
input.nextInt() won't consume anything not an int. It will throw an exception. You ignore the exception and try to consume an int. It's still not an int. Same exception. Infinite loop. Add another input.nextLine() in your catch block.
The algorithm should take in 3 integers to an ArrayList. If the input is not an integer, then there should be a prompt. When I execute my code the catch clause is executed, but the program runs into a infinite loop. Could someone guide me into the right direction, I appreciate the help. :-D
package chapter_08;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class IntegerList {
static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter = 1;
int inputNum;
do {
System.out.print("Type " + counter + " integer: " );
try {
inputNum = input.nextInt();
numbers.add(inputNum);
counter += 1;
}
catch (Exception exc) {
System.out.println("invalid number");
}
} while (!(numbers.size() == 3));
}
}
That is because when the next int is read using nextInt() and it fails, the Scanner still contains the typed contents. Then, when re-entering the do-while loop, input.nextInt() tries to parse it again with the same contents.
You need to 'flush' the Scanner contents with nextLine():
catch (Exception exc) {
input.nextLine();
System.out.println("invalid number");
}
Notes:
You can remove the counter variable, because you're not using it. Otherwise, you could replace counter += 1 by counter++.
You can replace while (!(numbers.size() == 3)) with while (numbers.size() != 3), or even better: while (numbers.size() < 3).
When catching exceptions, you should be as specific as possible, unless you have a very good reason to do otherwise. Exception should be replaced by InputMismatchException in your case.
If inputNum = input.nextInt(); cannot be fit into an int and a InputMismatchException is raised, the input of the Scanner is not consumed.
So after the catch, it loops and it goes again here :
inputNum = input.nextInt();
with exactly the same content in the input.
So you should execute input.nextLine(); in the catch statement to discard the current input and allow a new input from the user.
Besides it makes more sense to catch InputMismatchException rather than Exception as other exception with no relation with a mismatch could occur and it would not be useful to display to the user "invalid number " if it is not the issue :
catch (InputMismatchException e){
System.out.println("invalid number ");
input.nextLine();
}
You should to use a break; in your catch(){} like so :
try {
inputNum = input.nextInt();
numbers.add(inputNum);
counter += 1;
} catch (Exception e) {
System.out.println("invalid number ");
break;
}
So if one input is not correct break your loop.
try changing
inputNum = input.nextInt();
to
String inputText=input.next();
inputNum = Integer.valueOf(inputText);
it works perfectly well.
You need to move the scanner to the next line. Add this line of code below the error message in the catch section.
input.nextLine();
I need to build an array with 10 entries that the program prompts from the user, if the first entry is 9999, i need to program to quit. I also need to use try/catch for errors. Below is what I have but I can't get the variable 'number' to be recognized throughout when I input the try/catch loop... HELP!!!
public static void main(String[] args) {
int nextIndex = 1;
int[] numberFun;
numberFun = new int [10]; //creates the array with 10 entries
Scanner Keyboard = new Scanner (System.in);
int entry = 0;
//I'm trying to get the first entry to determine if it equals 9999 with this section
int firstNumber=0;
System.out.println ("Please enter a number");
firstNumber = Keyboard.nextInt();
numberFun[0] = firstNumber;
if (firstNumber != 9999)
{
while (entry < 9) //this loop is supposed to obtain the other 9 entries for the array from the user
{
int number;
System.out.println ("Please enter a number");
try // this is supposed to provide an error if the user enters something that is not a number
{
number = Keyboard.nextInt();
}
catch (Exception ex)
{
//display error message here
}
numberFun[nextIndex] = number;
++nextIndex;
++entry;
}
}
else
{
System.err.println("Command Accepted. Exiting Program.");
}
it works properly until I put the try/catch in.
Change,
int number;
to
int number = 0;
The variable that you are accessing later in the program needs to be initialized because Java will not compile if there's no guarantee that the variable you're using does not have a value to be worked with. Since you did not give number an initial value when you declared it, yet still use a try catch block to access it, Java won't know for sure whether number will have a value by the time it reaches the try catch block, which is why it's not currently working.
write firstNumber = Keyboard.nextInt(); in try catch block
and you need to initialize int number; before use
My code is supposed to take float value inputs from a user and once the user inputs 2 invalid inputs in a row (non float) the program stops and sums up the valid inputs and spits out the sum to the user. Here is the code:
System.out.println("Please input a set of float values.");
Scanner keyboard = new Scanner(System.in);
int tries = 0;
int maxTries = 2;
double sum = 0;
while (tries < 2) {
try {
while (keyboard.hasNext()){
sum += keyboard.nextDouble();
tries = 0; // reset counter because of valid input
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Float values "
+ "only please.");
tries += 1; // tries +1 because invalid input
}
}
System.out.printf("The sum of your inputs is: %d", sum);
My exception is being thrown prematurely, once I put in one invalid input the program stops and sums up. I can't figure out how to allow the user two consecutive invalid (non float) inputs and then throw the exception. Thanks.
try{
Scanner keyboard = new Scanner(System.in);
int tries = 0;
int maxTries = 2;
double sum = 0;
while (tries < 2) {
try {
while (keyboard.hasNext()){
double d = keyboard.nextDouble();
sum += d;
tries = 0; // reset counter because of valid input
}
}
catch (InputMismatchException e) {
System.out.println("Invalid input. Float values "
+ "only please.");
tries += 1; // tries +1 because invalid input
keyboard.nextLine();
}
}
System.out.printf("The sum of your inputs is: %f", sum);
}catch(Exception e){
e.printStackTrace();
}
The exception is thrown twice because there is still input in the keyboard scanner, and it attempts to continue reading. 'flush' it by reading in a nextline.
Also, on the output, print it with a %f
Scanner gives you hasNext and hasNextXXX where XXX is type you want precisely to avoid throwing exceptions.
Anyway if user provides invalid input it will stay in stream until you consume it. You can easily do it with next() or (sometimes better) with nextLine() method. So avoid using Exceptions as main part of your flow control logic.
So change your code and instead of hasNext which allows any kind of data, use hasNextDouble().
BTW to print floating-point number you need to use %f, %d is for integers.
Scanner keyboard = new Scanner(System.in);
int tries = 0;
int maxTries = 2;
double sum = 0;
while (tries < maxTries) {
if (keyboard.hasNextDouble()) {
sum += keyboard.nextDouble();
tries = 0; // reset counter because of valid input
} else {
System.out.println("Invalid input. Float values "
+ "only please.");
keyboard.next();// consume one invalid token from user input
tries += 1; // tries +1 because invalid input
}
}
System.out.printf("The sum of your inputs is: %f", sum);
Example:
Input: 1 2 3 b 4 foo bar
Output:
1 2 a 3 a 4 aa a
Invalid input. Float values only please.
Invalid input. Float values only please.
Invalid input. Float values only please.
The sum of your inputs is: 10,000000
The easier way to handle this is to read each input line as a string (keyboard.nextLine). Then try Double.parseDouble to convert into a double, catchinh any NumberFormatException to check number of tries etc.