Just a little confused as to what is happening here. The point of this error trap is, for example, the user inputs 3 numbers/letters instead of a 4 digit number. This error trap was designed loop the question until the user gets it right. However it instead loops the error message. Can anyone give some pointers as to what is going on?
JFrame Error = new JFrame ();
String input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
while (true){
try{
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
You need to move code for ask the input to the loop.
JFrame Error = new JFrame ();
String input = null;
while (true){
try{
input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
As JacobM mentioned, you need to ask for the input inside the while loop. When the catch clause terminates, the next thing your code does will be the first thing in the while loop.
JFrame Error = new JFrame ();
while (true){
String input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
try{
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
catch (Exception e){
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
You need to ask for a new value, inside the loop. change it to:
String input;
try {
while (true){
input = JOptionPane.showInputDialog(null,"Enter the 4 digit resistor values:");
int numInput = Integer.parseInt (input);
if (numInput >= 1000) {
break;
}
else {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(Error,"Invalid Input.");
}
Related
In my task I need to put InputMismatchException when user tries to enter some values. User get some numbers from 1 to some number (simptoms.lenght).
int number=0;
do{
System.out.printf("Choose %d simptoms: \n", number+1);
for(int j=0; j< simptomi.length;j++){
System.out.printf("%d. %s %s\n", j + 1, simptoms[j].getName(),
simptoms[j].getValue());
}
System.out.print("Choose: ");
while(!scanner.hasNextInt()){
System.out.println("Please enter number!");
scanner.next();
}
number=scanner.nextInt();
scanner.nextLine();
if(number<0 || number> simptoms.length){
System.out.println("Error, choose again");
}
}while(number<0 || number> simptoms.length);
After this code I tried to do this:
instead of while(!scanner.hasNextInt()) I tried with try and I get this message:
Declaration, final or effectively final variable expected.
Is this the right way of replacing while loop or I should try to add something else.
I'm thinking about boolean = false and somehow try with that but I don't understand how to implement it properly.
I tried this:
try{
number=scanner.nextInt();
scanner.nextLine();
}
catch (InputMismatchException ex){
System.out.println("Please, enter number!");
}
Try it out! hope it helps!
try {
do {
number = scanner.nextInt();
if (!Character.isAlphabetic(number)) {
if (number > simptoms.length) {
System.out.println("Error, choose again");
System.out.println("Please enter number!");
}
}
} while (number != -1);
} catch (InputMismatchException e) {
System.out.println("Enter number");
}
I have code to check for non numbers but also wish to include a check for negative numbers. If the number is negative or not a number, they have to re-enter info. I tried putting an if(depValue < 0).... after try{ and before catch but that didn't work. It doesn't make sense to me if I were to put the if statement after the while loop.
String depIn = "";
BufferedReader depositInput = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("Amount to deposit: ");
depIn = depositInput.readLine();
double depValue = 0.00;
try{
depValue = Double.parseDouble(depIn);
break;
}
catch(NumberFormatException ne){
System.out.println("You did not enter a number!");
}
}
You can break out of the loop when you have the number you need.
double depValue;
while(true){
System.out.print("Amount to deposit: ");
depIn = depositInput.readLine();
try {
if ((depValue = Double.parseDouble(depIn)) > 0)
break;
System.out.println("The number needs to be positive!");
} catch(NumberFormatException ne) {
System.out.println("You did not enter a number!");
}
}
Put it in the same try catch block, and just display the error message from the caught NumberFormatException
try{
depValue = Double.parseDouble(depIn);
if (depValue < 0) throw new NumberFormatException("Negative value not acceptable!");
break;
}
catch(NumberFormatException ne){
ne.printStackTrace();
}
so what I am trying to do is have the user input a valid coordinate in a matrix, that is an INT which is greater than -1,
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
the problem is that it loops endlessly after entering a not valid input
int R is the size of the row
int C is the size of the collumn
Your problem is that you're not handling the error you're catching.
If you'll provide wrong format of number for the nextInt() method, then the InputMismatchException will be thrown. Then because the catch does nothing, the loop will continue (start from begining) and the scanner will read the same incorrect value, and so on...
So instead of this:
catch (InputMismatchException e) {
}
Try this:
catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}
This way you'll force scanner to move past the last incorrect input.
EDIT:
You're loop is also broken because you do break after reading the input. In that case if you'll put the negative number you'll break as well and won't check the loop condition. Remove the break statement and it will work as expected:
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
EDIT2:
public static void main(final String args[])
{
int maxRowsNumber = 10;
int maxColsNumber = 10;
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
System.out.println("Inserted RowsNumber: " + coordinates[0]);
System.out.println("Inserted RowsNumber: " + coordinates[1]);
}
Output:
Please enter a valid row number: 11
Please enter a valid row number: 22
Please enter a valid row number: 10
Please enter a valid col number: 11
Please enter a valid col number: 2
Inserted RowsNumber: 10
Inserted RowsNumber: 2
If by "not valid input" you mean "not any kind of integer", then your scanner will fail each time it tries to read another integer, so you'll hit your catch, and do nothing to stop the loop. Maybe you intended to set check to false in such circumstances? Or maybe you meant to put the break in each catch?
Using a break when a valid integer is read isn't right, because it might be a negative integer, which your loop guard says you don't want.
This is basically the same as what your doing, I just tried to improve it a little bit by removing hardcoded values, made variables more descriptive, and included input validations.
final int ROW = 0;
final int COL = 1;
int coordinates[] = new int[2];
coordinates[ROW] = -1;
coordinates[COL] = -1;
boolean isInputValid = true;
Scanner scanner = new Scanner(System.in);
do {
try {
System.out.print("Please enter a valid row number:\t");
coordinates[ROW] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false; //if the input is not int
}
} while (!isInputValid && (coordinates[ROW] < 0) //do this until the input is an int
|| (coordinates[ROW] > R)); //and it's also not less than 0 or greater than R
//same logic applies here
do {
try {
System.out.print("Please enter a valid col number:\t");
coordinates[COL] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException nfe) {
isInputValid = false;
}
} while (!isInputValid && (coordinates[COL] < 0)
|| (coordinates[COL] > C));
Hope this helps.
do {
try {
System.out.println("how many times");
stringy = scanner.next();
rollnumber = Integer.parseInt(stringy);
if (stringy.equals("q")){
System.exit(0);
}
nigh = 2;
} catch (Exception e) {
System.out.println("invalid. re-enter");
scanner.nextLine();
}
} while (nigh == 1);
I'm not sure what I'm doing wrong. Its supposed to read the string but it still obviously doesn't register it in the system.exit. Please explain to me and examples would be very nice! thanks!
It will never reach the condition that checks for "q", since it will get an exception in parseInt.
If you type "q", parseInt would throw NumberFormatException before your condition that checks for "q".
You should move your rollnumber= Integer.parseInt(stringy); line to be after the condition.
My suggestion (without the System.exit()) :
boolean quit = false;
do {
try {
System.out.println("how many times");
stringy= scanner.next();
if (stringy.equals("q")) {
quit = true;
} else {
rollnumber= Integer.parseInt(stringy);
}
}
catch (Exception e)
{
System.out.println("invalid. re-enter");
scanner.nextLine();
}
} while (!quit);
Try this:
do {
try {
System.out.println("how many times");
stringy = scanner.next();
if (stringy.equals("q")){
System.exit(0);
}
rollnumber = Integer.parseInt(stringy);
nigh = 2;
}catch (Exception e) {
System.out.println("invalid. re-enter");
scanner.nextLine();
}
} while (nigh == 1);
I think you are not going out of the while-loop when you try to exit your app. Maybe you can try and add a return statement in the if after you try to exit your app.
*EDIT: Okay after fixing the try catch error I get a problem in the catch {.. when it prints.
*, Basically when I say I want to play again it continues the game as it should but it also prints the first catch and then asks for an input at line 23.
if (decision.equalsIgnoreCase("yes"))
{
ai = (int)(Math.random()*101);
System.out.println("From 0 to 100, what number do you think I have generated?");
tryCatch = true;
loop = true;
rtrn = true;
while (tryCatch == true)
{
while (loop == true)
{
try
{
guess = Integer.parseInt(iConsole.nextLine());
if (guess >= 0)
{
loop = false;
}
}
catch (NumberFormatException e)
{
System.out.println("Invalid input. Please try again.");
}
catch (InputMismatchException e)
{
System.out.println("Invalid input. Please try again!");
}
}
Hi this is my first post so if I get the code formatting on the forum wrong I'll edit it.
Right now I'm coding a game in java eclipse where the cpu generates a number and the user has to guess it. I am using the scanner class for most of this. What I am having trouble doing is creating a try catch to check the user input if it is a valid Integer.
What ends up happening is that the code block below it doesn't recognize the already-initialized variable.
package ics3U;
import java.util.*;
import java.io.*;
public class highLow
{
static public void main (String args[]) throws IOException
{
String name;
String decision;
String decision2;
int ai;
int guess;
int counter = 1;
boolean fullGame = true;
boolean tryCatch = true;
boolean rtrn = true;
Scanner iConsole = new Scanner(System.in);
System.out.println("Hello! Welcome to HiLo!");
System.out.println("What is your full name?");
name = iConsole.nextLine();
System.out.println("Hello " + name + "! Would you like to play?");
decision = iConsole.nextLine();
while (fullGame == true)
{
if (decision.equalsIgnoreCase("yes"))
{
ai = (int)(Math.random()*101);
System.out.println("From 0 to 100, what number do you think I have generated?");
tryCatch = true;
rtrn = true;
while (tryCatch == true)
{
try
{
guess = Integer.parseInt(iConsole.nextLine());
}
catch (Exception e)
{
System.out.println("Invalid input. Please try again.");
}
while (guess != ai)
{
if (guess < ai)
{
System.out.println("Too low!");
guess = iConsole.nextInt();
}
else if (guess > ai)
{
System.out.println("Too high!");
guess = iConsole.nextInt();
}
counter = counter + 1;
}
System.out.println("Correct! You guessed it after " + counter + " tries!");
counter = ((counter - counter)+1);
System.out.println("Would you like to play again?");
while (rtrn == true)
{
decision2 = iConsole.next(); //finally..
if (decision2.equalsIgnoreCase("yes"))
{
fullGame = true;
tryCatch = false;
rtrn = false;
break; //do-while may be needed, have to bypass catch, 'break' works after restating value of tryCatch & rtrn
}
else if (decision2.equalsIgnoreCase("no"))
{
System.out.println("Goodbye.");
fullGame = false;
tryCatch = false;
rtrn = false;
iConsole.close();
}
else
{
System.out.println("Sorry?");
}
}
/*catch (Exception e)
{
System.out.println("Invalid input. Please try again.");
}
catch (NumberFormatException e)
{
System.out.println("Invalid input. Please try again.");
}
//More specific Exceptions, turn this on later
catch (InputMismatchException e)
{
System.out.println("Invalid input. Please try again!");
}*/
}
}
else if (decision.equalsIgnoreCase("no"))
{
System.out.println("Goodbye.");
fullGame = false;
tryCatch = false;
rtrn = false;
iConsole.close();
}
else
{
System.out.println("Sorry?");
decision = iConsole.nextLine();
}
}
}
}
Add a continue statement in your catch block. That way, if the user enters something that's not an integer and parsing fails, it will immediately try again rather than trying to run the rest of the loop.
try
{
guess = Integer.parseInt(iConsole.nextLine());
}
catch (Exception e)
{
System.out.println("Invalid input. Please try again.");
continue; // jump to beginning of loop
}
Try moving all your code after the catch block (in the loop) inside the try block after this line
guess = Integer.parseInt(iConsole.nextLine());
As you currently have it, anytime there is an exception in the parseInt, it will still try to process the unassigned guess instead of restarting the loop.
Since the statements are in a try block there's a chance that they will fail, and your program has a chance of trying to use a non-initialized variable. The solution is to initialize the variables to a default value that makes sense, i.e.,
int guess = -1; // some default value
You should also wrap the while loop around the try/catch block. Don't let the program progress until inputted data is valid.
boolean validGuess = false;
while (!validGuess) {
// prompt user for input here
try {
guess = Integer.parseInt(iConsole.nextLine());
if (/* .... test if guess is valid int */ ) {
validGuess = true;
}
} catch (NumberFormatException e) {
// notify user of bad input, that he should try again
}
}
You could even encapsulate all of this into its own method if you need to do similar things throughout the program.