I have a try-catch that is meant to catch anything that is not an integer. When I enter a non integer (e.g. 5.6) it tells me only integers are allowed and lets me try again (as it should). But if I enter a non-integer again it doesn't say anything and will keep taking inputs, leaving output blank.
if (choicesObjects == b) {
System.out.println("TEST 2");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
int lengthOfTriangle = 0;
try {
lengthOfTriangle = input.nextInt();
} catch(InputMismatchException e) {
System.out.println("\nError: user input must be an integer greater than 0.\n");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
input.next();
}
//method stuff
}
The try/catch statement is not a loop. It will always be executed once.
Of course, if there is a loop inside the try block, that block will keep executing until terminated. But such a loop requires an explicit command like while or for to be used.
Apparently what happens when entering a non-integer value (e.g., 5.6), is that the nextInt() statement throws an Exception and goes to the catch block. A better explanation can be given if the full code of the method is provided.
For this you could define a function, something like this should work
private int getNextInt(Scanner input) {
boolean isInt = false;
int userInput;
while(!isInt) {
try {
userInput = Integer.valueOf(input.next());
isInt = true;
} catch(NumberFormatException e) {
// Do nothing with the exception
}
}
return userInput;
}
This should run until an input given was an int and then return said int
You can update your code to something like this -
Scanner in = new Scanner(System.in);
int num = 0;
while(true) {
try{
num = in.nextInt();
break;
}catch(Exception e){
//print statements
System.out.println("Try again");
}
}
System.out.println("Done");
something like this
Boolean check = true;
while (check) {
if choicesObjects == b {
enter code here` System.out.println("TEST 2");
System.out.println("Object: Right triangle");
System.out.println("\nEnter length of Right triangle: ");
int lengthOfTriangle = 0;
try {
lengthOfTriangle = input.nextInt();
} catch(InputMismatchException e) {
System.out.println("\nError: user input must be an integer greater than 0.\n");
check = false;
System.out.println("Object: Right triangle");System.out.println("\nEnter length of Right triangle:");
input.next();
}
//method stuff
}
}
`
Related
I'm building a small program that checks if the user input is a number. The program runs but when my catch block catches an exception, it somehow exited the nested do-while loop it is in.
Here's my program :
package TESTCLASS;
import java.util.Scanner;
public class Apples {
static int readValidInt(Scanner in, String prompt, int min, int max){
int validUserInput;
int userInput = 0; //have to initialize this variable since I will be using it in a block, setting it to 0 for now
int checker =1;
while(!in.hasNextInt()) { //Makes sure that user inputs an Integer, not String, double, etc
System.out.println("Sorry, only numbers in integer form is allowed. Please enter your choice as an integer between 1 and 4");
in.next();
}
do {
do {
try {
userInput = in.nextInt();
checker = 0;
}
catch (Exception e) {
System.out.println("Exception detectedddd");
in.nextLine(); // This line is to *clear the buffer* for Scanner
}
}while (checker ==1 );
if ( userInput >= min && userInput <= max) {
System.out.println("you have chosen board " + userInput );
validUserInput = userInput;
}
else {
System.out.println(prompt);
validUserInput = 0;
}
}while (validUserInput==0);
return validUserInput;
}
// Main function
public static void main (String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Choose a board style");
readValidInt(input, "Bruh that's not valid", 1, 4);
}
}
Here is my output(As you can see, when I put "five", two things get printed out - "Exception detectedddd" & "Bruh that's not valid", but the latter sentence is part of the if else statement, which should not have been reached since there is an exception :
Choose a board style
100
Bruh that's not valid
five
Exception detectedddd
Bruh that's not valid
six
Exception detectedddd
Bruh that's not valid
10
Bruh that's not valid
1
you have chosen board 1
After the first input (100) you set checker = 0;. Since the value is too large you print "Bruh that's not valid" and stay within the outer loop.
That means that you read another value (five) which leads to the exception. However, since checker is already 0 (from the first pass) the inner loop is not repeated.
You need to reset checker to 1 before each start of the inner loop:
do {
checker = 1;
do {
try {
userInput = in.nextInt();
checker = 0;
}
catch (Exception e) {
System.out.println("Exception detectedddd");
in.nextLine(); // This line is to *clear the buffer* for Scanner
}
} while (checker == 1);
//... remainder of the outer loop
} while (validUserInput == 0);
I refreshing my Java skills, say we've got this code
public class HelloWorld extends Exception {
public static int tenMultiplication(int x) {
for (int i = 2; i < 11; i++) {
System.out.println(x * i);
}
return x;
}
public static String scanExpression() {
Scanner scan = new Scanner(System.in);
String exp = "";
do {
System.out.println("Please enter a number:");
try {
exp = scan.nextLine();
int result = Integer.parseInt(exp);
tenMultiplication(result);
} catch (NumberFormatException e) {
System.out.println("Please enter a number: ");
}
} while (exp.matches("-?\\d+") || exp == "exit");
return exp;
}
public static void main(String args[]) throws Exception {
scanExpression();
}
}
Program logic: Program asks for an input, and draws a row of multiplication table till 10; any time you can exit by typing "exit", everything else is an error.
Every time I write an incorrect number, it will simply catch an error and exit the program. What is the best way with going about iteratively catching errors if you consecutively type non-Ints and not "exit" to exit the program? I tried putting
exp = scan.nextLine();
int result = Integer.parseInt(exp);
tenMultiplication(result);
But when trying to write an error here, it throws the error again, which defeats the point of my try { } catch blocks.
You need to re-read the input in case NumberFormatException is caught, you can do it in a recursive way by by calling your function again
public static void scanExpression(Scanner scan) {
System.out.println("Please enter a number:");
try {
String exp = scan.nextLine();
if(exp.equals("exit"))
System.exit(0);
int result = Integer.parseInt(exp);
tenMultiplication(result);
} catch (NumberFormatException e) {scanExpression(scan);}
}
public static void main(String args[]) throws Exception {
Scanner scan = new Scanner(System.in);
scanExpression(scan);
}
After the catch block executes the program continues and goes to check the condition in the while statement. The while statement returns false for that condition so your program terminates. Plus you need to compare exp like this: exp.equals("exit").
Here are some changes I made to your loop.
do {
System.out.println("Please enter a number:");
try {
exp = scan.nextLine();
int result = Integer.parseInt(exp);
tenMultiplication(result);
} catch (NumberFormatException e) {
}
} while (!exp.equals( "exit") );
I made your catch block empty. The reasoning is that if it does catch invalid input from the user, "Please enter a number:" would print twice.
Also, I modified your while loop condition. Previously you had exp == "exit". This doesn't work the way you expect it to work. When comparing String values, always use `String1.equals(String2) to see if String1 and String2 are equal.
I had a bit of a hard time figuring this part out for a school project of mine.
So looking for a bit of clarification.
Generally, the user had to input a number (column) to insert a game piece.
However, if the user were to enter "q" the program would close down.
We were pointed into the direction of using "parseInt", however i am looking for a bit of clarification as to how this works?
while(response.equalsIgnoreCase("q"));
{
System.out.println("Do you want to play again?");
response = scan.next();
}
System.out.println("Do you want to play again?");
response = scan.next(); // this revisits the while loop that
// prompted the player to play.
import java.util.Scanner;
public class ScanInteger {
public static void main(String...args)throws Throwable {
int num = 0; String s= null;
System.out.print("Please enter a number : ");
Scanner sc = new Scanner(System.in);
do{
try{
s = sc.next();
num= Integer.parseInt(s);
System.out.println("You have entered: "+num+" enter again : ");
}catch(NumberFormatException e){
if(!s.equalsIgnoreCase("q"))
System.out.println("Please enter q to quit else try again ==> ");
}
}while(!s.equalsIgnoreCase("q"));
sc.close();
}
}
See http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)
public static int parseInt(String s)
throws NumberFormatException
You want to apply a try-catch block around the Integer.parseInt(userInput) call to catch a NumberFormatException
In the catch body, you can set a flag that the input was invalid. Put the whole thing in a while loop based on the boolean isInputIsValid.
boolean isValidNumber = false, wantsToQuit = false;
while (!isValidNumber) {
// Ask user for a value any way you want and save it to userInput
String userInput = "";
try {
Integer.parseInt(userInput);
isValidNumber = true;
} catch (NumberFormatException e) {
isValidNumber = false;
if (userInput.equals("q")) {
wantsToQuit = true;
break;
}
}
}
wantsToQuit is not a necessary variable, just showing what the purpose of that section is
Hey guys so i've been trying to answer this question for hours:
Write a program that asks the user to input a set of floating-point values. When the
user enters a value that is not a number, give the user a second chance to enter the
value. After two chances, quit reading input. Add all correctly specified values and
print the sum when the user is done entering data. Use exception handling to detect
improper inputs.
I've tried a few different things but i always have the same problem. Once something that isn't a number is given as input, the program outputs the message prompting for another input however the chance is not given, that is to say after 1 incorrect input it prints that message and jumps straight to printing the sum. The best i could do is below i'm just not sure how to approach this problem. Any help is greatly appreciated.
import java.util.Scanner;
import java.util.InputMismatchException;
public class q6{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
boolean firstChance = true;
boolean secondChance = true;
double sum = 0;
while (secondChance){
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
firstChance = false;
}
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
System.out.print("The sum of the entered values is " + sum);
}
}
i'm just not sure how to approach this problem
Pseudocode could be as follows:
BEGIN
MAX_INPUT = 2;
i = 0;
WHILE i < MAX_INPUT
TRY
num = GET_NUM();
CATCH
continue;
FINALLY
i++
END WHILE
END
Since the parsing of input to double is not successful, the scanner does not go past the given input. From javadoc Scanner
Scans the next token of the input as a double. This method will throw
InputMismatchException if the next token cannot be translated into a
valid double value. If the translation is successful, the scanner
advances past the input that matched.
Since the translation is not successful, it does not advance. So, in the catch block you could call in.next() to skip the token.
You could use an integer counter instead of the boolean variables firstChance and secondChance and do something like:
int attempts = 0;
while(attempts < 2) {
try {
//Get user input - possible exception point
//Print sum
} catch(InputMismatchException e) {
attempts++;
//Continue?
}
}
import java.util.*;
public class q6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double inputNumber, sum = 0.0;
int correctCount = 0, wrongCount = 0;
while(wrongCount <=1) {
System.out.println("Please enter a numeric floating value:");
try {
inputNumber = in.nextDouble();
correctCount++;
sum += inputNumber;
if(correctCount >= 2)
break;
} catch(InputMismatchException e) {
wrongCount++;
in = new Scanner(System.in);
continue;
}
}
System.out.println(sum);
}
}
You need to break your while loop when you encounter a "bad" input. Then, you'll need to set firstChance to true again, so you can access the second while, you also will need a counter that counts the number of the attempts (I named it chances):
int chances = 0;
while (secondChance){
firstChance = true;
try{
while (firstChance){
try{
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
}
catch (InputMismatchException ex){
chances ++;
in = new Scanner(System.in);
firstChance = false;
}
if(!firstChance && chances < 2)
break;
if(chances >= 2) {
System.out.print("Please enter a number to continue or something else to terminate: ");
double input = in.nextDouble();
sum = sum + input;
firstChance = true;
}
}
}
catch (InputMismatchException e){
secondChance = false;
}
}
As stated in my comment, in order to not deal with Scanner wrong read, it would be better to use Scanner#nextLine() and read the data as String, then try to parse it as double using Double#parseDouble(String) since this method already throws NumberFormatException and you can handle this error. Also, it would be better that your code could handle more than 1 request (if your teacher or somebody else asks to do this):
final int REQUEST_TIMES = 2;
double sum = 0;
for(int i = 1; i <= REQUEST_TIMES; i++) {
while (true) {
try {
if (i < REQUEST_TIMES) {
System.out.print("Please enter a number: ");
} else {
System.out.print("Please enter a number to continue or something else to terminate: ");
}
String stringInput = in.nextLine();
double input = Double.parseDouble(stringInput);
sum += input;
} catch (NumberFormatException nfe) {
System.out.println("You haven't entered a valid number.");
break;
}
}
}
The logic is to read the input once, if it is correct then display the sum, else read the input again and display the sum if the input is correct.
public class q6 {
static int trial = 0;
public static void main(String[] args) {
double sum = 0;
while (trial <= 2) {
Scanner in = new Scanner(System.in);
try {
trial++;
System.out.print("Please enter a number: ");
double input = in.nextDouble();
sum = sum + input;
trial=3;
} catch (InputMismatchException ex) {
trial++;
if (trial == 4){
System.out.println("You have entered wrong values twice");
}
}
}
if (trial <= 3){
System.out.print("The sum of the entered values is " + sum);
}
}
The above program is just a rough idea, you can improve this to adapt to your need.
I have been trying to stop the exceptions but I cannot figure out how.
I tried parseInt, java.util.NormalExceptionMismatch etc.
Does anyone have any insight how to fix this problem? Formatting is a bit off due to copy and paste.
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
if (!intFind.hasNextInt())
intFind.next();
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
}
}while(select < 0)
Other methods I have tried :
do
{
System.out.print(
"How many integers shall we compare? (Enter a positive integer):");
select = intFind.nextInt();
{
try{
select = intFind.nextInt();
}catch (java.util.InputMismatchException e)
{
// Display the following text in the event of an invalid input
System.out.println("Invalid input!");
return;
}
}
}while(select < 0)
It seems to me that you want to skip everything until you get an integer. This code here skips any input except an integer.
As long as there is no integer available (while (!in.hasNextInt())) discard the available input (in.next). When integer is available - read it (int num = in.nextInt();)
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (!in.hasNextInt()) {
in.next();
}
int num = in.nextInt();
System.out.println("Thank you for choosing " + num + " today.");
}
}
Quick sample of how to catch exceptions:
int exceptionSample()
{
int num = 0;
boolean done = false;
while(!done)
{
// prompt for input
// inputStr = read input
try {
num = Integer.parseInt(inputStr);
done = true;
}
catch(NumberFormatException ex) {
// Error msg
}
}
return num;
}
IMO, the best practice is to use nextLine() to get a String input, then parseInt it to get the integer. If unparsable, just complain back to the user and request re-entry.
Remember you may have to do a second nextLine() (discard the input) to clear up the buffer.