Problems with exception handling using try and catch - java

I'm trying to use try and catch. If the entered input isn't valid the loop sould repeat and ask the user for input again, but it's not working. When I type something wrong it just repeats the System.out.println.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class Price
{
public static void main(String[] args)
{
userInput();
}
public static void userInput()
{
Scanner scan = new Scanner(System.in);
int x = 1;
int month, day, year;
do {
try {
System.out.println("Please enter a month MM: ");
month = scan.nextInt();
if(month>12 && month<1)
{
System.out.println("FLOP");
}
x=2;
}
catch(Exception e){
System.out.println("not today mate");
}
}
while(x==1);
}
}

this is a working solution to your problem
public static void userInput(){
Scanner scan = new Scanner(System.in);
int x = 1;
int month, day, year;
System.out.println("Please enter a month MM: ");
month = scan.nextInt();
boolean i = true;
while(i == true)
{
if(month < 12 && month > 1)
{
System.out.println("FLOP");
i = false;
}
else if(month >= 12 || month <= 1)
{
System.out.println("not today mate");
month = scan.nextInt();
}
}
}

As a general rule, exceptions are used for exceptional circumstances, not to drive the logic of a program. Validating inputted data is not an exceptional circumstance in this case. It's a normal state of affairs that a user might make an error and enter an incorrect number. Put the input in a loop and repeat until a correct value is entered (perhaps with an option for the user to cancel).

First your condition is wrong.
You have:
if(month>12 && month<1)
{
System.out.println("FLOP");
}
So month cannot be bigger than 12 and at the same time less than 1.
I think you wanted to put OR instead of AND, e.g.
if(month > 12 || month < 1)
{
System.out.println("FLOP");
}
As for the exception, it might occur when user enters non numeric value or input is exausted.
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

Related

Java Error when text input instead of number

I am just trying to get code to work where the code asks again for an answer, if text or a symbol is entered, instead of a required integer:
import java.util.Scanner;
class timecalc {
int hrs = 0;
int min = 0;
static int hourflag = 0;
static int minflag = 0;
Scanner sc = new Scanner(System.in);
public int getHours() {
try {
hourflag = hourflag + 1;
if (hourflag > 1) {
System.out.println("Invalid month Please enter hours again:");
}
System.out.println("Enter month:");
return hrs = sc.nextInt();
} catch (InputMisMAtchException e) {
System.out.println("entered invalid input " + e);
}
}
Have reviewed answers already given but cant get a workable solution
Any ideas?
I won't give you the entire code, but just a hint or psuedo-code. As an exercise you can implement it as per your requirement.
System.out.println("Enter month:");
while (true) {
try {
int min = sc.nextInt();
break;
} catch (InputMismatchException ex) {
System.err.println("Invalid input, please enter again");
sc.nextLine(); // <----- advance the scanner
}
}
Here the logic is to loop until we get the right input. If it is an invalid input, the loop never breaks.
Also as a side-note, I would recommend you to create just one method to fetch correct inputs and call it respectively from other methods. Rather than duplicating this logic everywhere.

Where should I put the variable scanner declaration? "int figureNumber = stdin.nextInt();"

I want to make it so that a user entering the wrong data type as figureNumber will see a message from me saying "Please enter an integer" instead of the normal error message, and will be given another chance to enter an integer. I started out trying to use try and catch, but I couldn't get it to work.
Sorry if this is a dumb question. It's my second week of an intro to java class.
import java. util.*;
public class Grades {
public static void main(String args []) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Please enter an integer: ");
int grade = stdin.nextInt();
method2 ();
if (grade % 2 == 0) {
grade -= 1;
}
for(int i = 1; i <=(grade/2); i++) {
method1 ();
method3 ();
}
}
}
public static void main(String args[]) {
Scanner stdin = new Scanner(System.in);
System.out.println();
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
while (!stdin.hasNextInt()) {
System.out.print("That's not a number! Please enter a number: ");
stdin.next();
}
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for (int i = 1; i <= (figureNumber / 2); i++) {
whale();
human();
}
}
You need to check the input. The hasNextInt() method is true if the input is an integer. So this while loop asks the user to enter a number until the input is a number. Calling next() method is important because it will remove the previous wrong input from the Scanner.
Scanner stdin = new Scanner(System.in);
try {
int figureNumber = stdin.nextInt();
eagle();
if (figureNumber % 2 == 0) { //determines if input number of figures is even
figureNumber -= 1;
}
for(int i = 1; i <=(figureNumber/2); i++) {
whale();
human();
}
}
catch (InputMismatchException e) {
System.out.print("Input must be an integer");
}
You probably want to do something like this. Don't forget to add import java.util.*; at the beginning of .java file.
You want something in the form:
Ask for input
If input incorrect, say so and go to step 1.
A good choice is:
Integer num = null; // define scope outside the loop
System.out.println("Please enter a number:"); // opening output, done once
do {
String str = scanner.nextLine(); // read anything
if (str.matches("[0-9]+")) // if it's all digits
num = Integer.parseInt(str);
else
System.out.println("That is not a number. Please try again:");
} while (num == null);
// if you get to here, num is a number for sure
A do while is a good choice because you always at least one iteration.
It's important to read the whole line as a String. If you try to read an int and one isn't there the call will explode.
You can actually test the value before you assign it. You don't need to do any matching.
...
int figureNumber = -1;
while (figureNumber < 0) {
System.out.print(" Welcome! Please enter the number of figures for your totem pole: ");
if (stdin.hasNextInt()){
figureNumber = stdin.nextInt(); //will loop again if <0
} else {
std.next(); //discard the token
System.out.println("Hey! That wasn't an integer! Try again!");
}
}
...

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 :)

Java validate only values between 1 and 3

I am trying to only accept integers between the values of 1 and 3 using a while loop and nested if statement in Java.
Anything outside of this range, produces an error message
The program should only accept integers between 1 and 3, any strings of text or decimal values should also produce the same error message and loop back to the original print statement (enter a number: )
The code below runs without any compiler errors although the statement || (a < 1 || a > 3)) will always produce the error message, regardless of the value.
If I was to delete this statement, the program will run and only accept integers of any value, (error message appearing when a string or decimal value is entered)
Could anyone help range this program, only accepting values of between 1 and 3, thanks.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
while (true) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext() || (a < 1 || a > 3)) {
System.out.println("Oops! ");
input.nextLine();
}
else {
a = input.nextInt();
break;
}
}
input.close();
System.out.println("a = " + a);
}
}
Make sure to be careful of the order of expressions. If one of the 3 statements you wrote happens to be true then the code in the if curly braces will execute. You likely want something like this
if (!input.hasNextInt() || !input.hasNext()){
if ((a > 1 || a < 3)){
YourCode
}
}
The biggest issue is that you need to remember that initially your integer "a" is set to "0". This always catches your first if condition meaning that a is never set!
You are not updating the value of a, so it's 0 all the time.
import java.util.Scanner;
public class Validate {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a = 0;
boolean loop = true;
while (loop) {
System.out.print("enter a number: ");
if (!input.hasNextInt() || !input.hasNext()) {
System.out.println("Oops! ");
input.nextLine();
} else {
a = input.nextInt();
if (a <= 3 && a >= 1)
loop = false;
else {
System.out.println("Oops! ");
input.nextLine();
}
}
}
input.close();
System.out.println("a = " + a);
}
}
EDIT:

Looping do...while uncertainty

In the catch block, I'm trying to correct for user bad-input issues. When testing it, if I use the "break" keyword, it doesn't jump to the initial question. If I use "continue", it loops infinitely. "Sc.next();" doesn't seem to resolve it either.
Here's the relevant part of the code.
public class ComputerAge {
private static int age;
private static int year;
private static int month;
private static int date;
private static Calendar birthdate;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Enter the numeral representing your birth month: ");
do {
try {
month = sc.nextInt();
} catch (InputMismatchException ime){
System.out.println("Your respone must be a whole number");
break;
}
} while (!sc.hasNextInt());
In order to fix the problem, we should identify what we want to accomplish at the end.
We want the month to be a numeral month, that is number > 0.
Thus:
If a user fill a correct number month will be filled.
Otherwise, Exception will be thrown and month will stay as '0'.
Conclusion: We want our program will keep running when month is equals 0.
The solution is pretty simple:
While condition should be:
while (month == 0);
And you should change break to sc.next().
The problem with your approach is that when you call sc.nextInt() and it throws an exception, Scanner does not advance its reading position. You need to advance the reading pointer by calling sc.next() inside the catch block instead of the break:
do {
try {
month = sc.nextInt();
} catch (InputMismatchException ime){
System.out.println("Your respone must be a whole number");
sc.next(); // This will advance the reading position
}
} while (!sc.hasNextInt());
I think you should use an infinite loop, and when the input is correct (no exception thrown), use break to finish the loop:
public static void main(String args[])
{
System.out.print("Enter the numeral representing your birth month: ");
do {
try {
int month = sc.nextInt();
break;
} catch (InputMismatchException ime) {
System.out.println("Your respone must be a whole number");
sc.nextLine();
}
} while (true);
}
Also, you will have to use sc.nextLine() in the catch block because when you enter some input and press Enter, a new-line character is added, and nextInt() doesn't read it. You have to use nextLine() to consume that character. For further information about this issue you could read this.
First of all, you have to avoid use try/catch in iteratives sentences in order to improve perfomance.
You can recode for the break to work in this way (keep in mind that de do-while will execute at least one time, so if your scanner retrieve null value, you will have nullPointer)
try {
while (sc != null && !sc.hasNextInt()) {
month = sc.nextInt();
}
} catch (InputMismatchException ime){
System.out.println("Your respone must be a whole number");
}
Make sure you can get the integer first, and use regular expressions. Don't use exceptions if possible to enforce code logic.
int month;
boolean correct = false;
while (!correct && sc.hasNextLine())
{
String line = sc.nextLine();
if (!line.matches("^[0-9]+$"))
{
System.out.println("Your response must be a whole number");
correct = false;
}
else
{
month = Integer.parseInt(line);
correct = true;
}
}

Categories