Getting IllegalStateException in my program? - java

Stacktrace Here
import java.util.*;
public class AccountClient {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean infiniteLoop = true;
boolean invalidInput;
int id;
// Create array of different accounts
Account[] accountArray = new Account[10];
//Initialize each account array with its own unique id and a starting account balance of $100
for (int i = 0; i < accountArray.length; i++) {
accountArray[i] = new Account(i, 100);
}
do {
try {
//inner loop to detect invalid Input
do {
invalidInput = false;
System.out.print("Enter an id: ");
id = input.nextInt();
if (id < 0 || id > 9) {
System.out.println("Try again. Id not registered in system. Please enter an id between 0 and 9 (inclusive).");
invalidInput = true;
input.nextLine();
}
} while (invalidInput);
boolean exit;
do {
exit = false;
boolean notAnOption;
int choice;
do {
notAnOption = false;
System.out.print("\nMain Menu\n1: check balance\n2: withdraw\n3: deposit\n4: exit\nEnter a choice: ");
choice = input.nextInt();
if (choice < 1 || choice > 4) {
System.out.println("Sorry, " + choice + " is not an option. Please try again and enter a number between 1 and 4 (inclusive).");
notAnOption = true;
}
} while(notAnOption);
switch (choice) {
case 1: System.out.println("The balance for your account is $" + accountArray[id].getBalance());
break;
case 2: {
boolean withdrawFlag;
do {
System.out.print("Enter the amount you would like to withdraw: ");
double withdrawAmount = input.nextInt();
if (withdrawAmount > accountArray[id].getBalance()) {
System.out.println("Sorry, you only have an account balance of $" + accountArray[id].getBalance() + ". Please try again and enter a number at or below this amount.");
withdrawFlag = true;
}
else {
accountArray[id].withdraw(withdrawAmount);
System.out.println("Thank you. Your withdraw has been completed.");
withdrawFlag = false;
}
} while (withdrawFlag);
}
break;
case 3: {
System.out.print("Enter the amount you would like to deposit: ");
double depositAmount = input.nextInt();
accountArray[id].deposit(depositAmount);
System.out.println("Thank you. You have successfully deposited $" + depositAmount + " into your account.");
}
break;
case 4: {
System.out.println("returning to the login screen...\n");
exit = true;
}
break;
}
} while (exit == false);
}
catch (InputMismatchException ex) {
System.out.println("Sorry, invalid input. Please enter a number, no letters or symbols.");
}
finally {
input.close();
}
} while (infiniteLoop);
}
}
The exception code:
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
at java.util.Scanner.next(Scanner.java:1465)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at playground.test.main.Main.main(Main.java:47)
Hello, I made a basic program that uses a class called account to simulate an ATM machine. I wanted to throw an exception if the user didn't type in a letter. This worked fine, however I needed to make it loop so the program didn't terminate after it threw the exception. To do this I just put the try catch in the do while loop I had previously. When I did this though, it's throwing an IllegalStateException every time I type in a letter or choose to exit an inner loop I have which takes the user back to the loop of asking them to enter their id. What is an IllegalStateException, what is causing it in my case, and how would I fix this? Thanks.

It's fairly simple, after you catch the exception the finally clause gets executed. Unfortunately you're closing the scanner within this clause and Scanner.close() closes the underlying input stream (System.in in this case).
The standard input stream System.in once closed can't be opened again.
To fix this you have to omit the finally clause and close the scanner when your program needs to terminate and not earlier.

Related

How do I include a question asking the user if they want to play again?

I am still new to Java and as such I am still figuring some things out. I have been having issues with including code asking the user if they want to play again. I have attempted putting it in the main class in a print statement which gave me an error. After that, I attempted putting it in the Guess.java class in multpile places but I just recieved errors. I have read up on the issue and some sites have suggested a while loop but I am unsure how to implement it into my current code. I have included both the main class which is called GuessingGame.java and the Guess.java class below. Thank you for any assistance that can be provided.
GuessingGame.java
public class GuessingGame {
public static void main(String[] args) {
new Guess().doGuess();
}
}
Guess.java
class Guess {
private int answer = 0;
int tries = 0;
Scanner input = new Scanner(System.in);
int guess, i;
boolean win = false;
int amount = 10;
public Guess() {
answer = generateRandomNumber();
}
//Generate a private number between 1 and a thousand
private int generateRandomNumber() {
Random rand = new Random();
return rand.nextInt(1000) + 1;
}
public void doGuess() {
while (!win) {
System.out.println("You are limited to ten attempts."
+ " Guess a number between 1 and 1000: ");
guess = input.nextInt();
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number"
+ " was: " + answer);
System.out.println("Do you want to play again?: ");
return;
}
if (guess > 1000) {
System.out.println("Your guess is out of the range!");
} else if (guess < 1) {
System.out.println("Your guess is out of the range!");
} else if (guess == answer) {
win = true;
tries++;
} else if (guess < answer && i != amount - 1) {
System.out.println("Your guess is too low!");
tries++;
} else if (guess > answer && i != amount - 1) {
System.out.println("Your guess is too high!");
tries++;
}
}
System.out.println("Congragulations! You guessed the number!"
+ "The number was: " + answer);
System.out.println("It took you " + tries + " tries");
}
}
You already found a good position for adding this functionality:
System.out.println("Do you want to play again?: ");
The first step now is to also tell the user what he/she should enter after that question:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
After that we need to get the user input of course:
int number;
//If the user enters e.g. a string instead of a number, the InputMismatchException
//will be thrown and the catch-block will be executed
try {
number = input.nextInt();
//If number < 0 OR number > 1
if(number < 0 || number > 1) {
//The rest of the try-block will not be executed.
//Instead, the following catch-block will be executed.
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
//Clears the scanner to wait for the next number
//This is needed if the user enters a string instead of a number
input.nextLine();
}
If you don't know about try-catch-statements yet, I suggest to read this explanation. For details about the InputMismatchException, please see the documentation.
The problem now is that the user only has one chance to enter 0 or 1. If the user makes a wrong input the program will just stop. One solution to this problem is to just put the code in a while-loop:
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
After this block, we can be sure that number is either 0 or 1. So now we can add a simple if-statement to check the value:
if(number == 0) {
new Guess().doGuess();
}
return;
So all in all the code looks like this:
System.out.println("Do you want to play again? (enter 0 for yes and 1 for no): ");
int number;
while(true) {
try {
number = input.nextInt();
if(number < 0 || number > 1) {
throw new InputMismatchException();
}
break;
}
catch(InputMismatchException e) {
System.out.println("Enter 0=yes or 1=no");
input.nextLine();
}
}
if(number == 0) {
new Guess().doGuess();
}
return;
Don't forget to add the following import-statements:
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.Random;
Try this. Basically, if the user responds with "yes" , we will call the function again.
if (tries > 9) {
System.out.println("You should be able to do better!"
+ " You have hit your ten guess limit. The number" + " was: " + answer);
System.out.println("Do you want to play again? (yes/no): "); // modified line
if("yes".equalsIgnoreCase(input.next())){ // newly added if block
answer = generateRandomNumber();
tries=0;
i=0;
win = false;
doGuess();
}
return;
}

Object not Being Initialized Due to Scope

Apologies for the long code I'm about to include. What I'm trying to do is save certain validated, user input variables to an object. I believe my issue is due to the variables scope, that's why I'm having the error customerAccount may not have been initialized.
If anybody could point me in the right direction, it'd be greatly appreciated.
import java.util.*;
import java.io.*;
public class ATM {
public void run() {
// USED FOR DEBUGGING PURPOSES. SET TO TRUE TO ENABLE DEBUGGING MODE
boolean debug = false, mainCheck = false, check = false;
Scanner input = new Scanner(System.in);
Scanner fInput = null;
int idNumber = 0;
String lastName, firstName, emailAddress, phoneNumber;
double startingBalance;
Client customerAccount;
File file = new File("accountData.txt");
if(!file.exists()) {
System.out.println("File does not exist within directory. Creating file now.");
PrintWriter output = null;
try {
output = new PrintWriter(file);
}
catch(IOException e) {
System.out.println("Something went wrong during file creation.");
}
finally {
if (output != null)
output.close();
}
}
ArrayList<Client> clientArr = new ArrayList<Client>();
try {
fInput = new Scanner(new File("accountData.txt"));
}
catch(Exception e) {
System.out.println("ERROR: File Not Found.");
e.printStackTrace();
}
while(fInput.hasNext()) {
try{
int tempID = fInput.nextInt();
String tempFName = fInput.next();
String tempLName = fInput.next();
String tempPNumber = fInput.next();
String tempEmail = fInput.next();
double tempBalance = fInput.nextFloat();
Client tempClient = new Client(tempID, tempFName, tempLName, tempPNumber, tempEmail, tempBalance);
tempClient.getAccount().setID(tempID);
clientArr.add(tempClient);
if(debug == true)
System.out.println(tempID+" "+tempFName+" "+tempLName+" "+tempPNumber+" "+tempEmail+" $"+tempBalance);
}
catch(NoSuchElementException e) {
System.out.println("ERROR: Missing a required data field.");
}
}
if(debug == true)
System.out.println(clientArr.size());
int menuChoice = 0;
while(menuChoice != 5) {
System.out.println("**********************************");
System.out.println("Thank you for choosing Java World Bank!");
System.out.println("Main Menu: ");
System.out.println("[1] Login as an existing user.");
System.out.println("[2] Display client list sorted by last name.");
System.out.println("[3] Display client list sorted by account number.");
System.out.println("[4] Create a new client.");
System.out.println("[5] Exit.");
System.out.println("====================================");
do {
try {
System.out.println("Enter your choice: ");
menuChoice = input.nextInt();
mainCheck = true;
}
// Checks if user enters an unexpected input (not a digit)
catch(InputMismatchException e) {
System.out.println("Invalid input! Please use a numeric value between 1 and 5.");
if(debug == true)
e.printStackTrace();
input.nextLine();
}
}while(!mainCheck);
switch(menuChoice) {
case 1:
System.out.println("Please enter your fist name: ");
input.nextLine();
String loginFName = input.nextLine();
while(loginFName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. First name needs to be all letters. Please try again.");
loginFName = input.nextLine();
}
System.out.println("Please enter your last name: ");
String loginLName = input.nextLine();
while(loginLName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. Last name needs to be all letters. Please try again.");
loginLName = input.nextLine();
}
final String searchFName = loginFName;
final String searchLName = loginLName;
int loginValidation = 0;
Optional<Client> queryResult = clientArr.stream().filter(value -> value.getFName().equals(searchFName)
&&value.getLName().equals(searchLName)).findFirst();
if(queryResult.isPresent()) {
System.out.println("User "+loginFName+" "+loginLName+" successfully logged into. Welcome back to Java World Bank.");
menuChoice = 5;
}
else
System.out.println("Login failed. Returning to main menu.");
break;
case 2:
System.out.println("Clients of Java World Bank, sorted by last name: ");
clientArr.sort( (p1, p2) -> p1.getLName().compareTo(p2.getLName()) );
for(Client client : clientArr)
System.out.println(client);
menuChoice = 5;
break;
case 3:
System.out.println("Clients of Java World Bank, sorted by ID: ");
clientArr.sort( (p1, p2) -> Integer.compare(p1.getAccount().getID(),
p2.getAccount().getID()));
for(Client client : clientArr)
System.out.println(client);
menuChoice = 5;
break;
case 4:
System.out.println("You are now creating a new client account with Java World Bank!");
System.out.println("Some information is required to create this account.");
System.out.println("What would you like your ID number to be? It must contain only integers.");
check = false;
do {
try {
System.out.println("Please enter your choice: ");
idNumber = input.nextInt();
check = true;
}
catch(InputMismatchException e) {
System.out.println("ERROR: ID must contain integers only!");
input.nextLine();
}
}while(!check);
startingBalance = 0;
check = false;
// Continiously prompts user to enter valid input
do {
try {
System.out.println("What will be your starting balance?");
startingBalance = input.nextDouble();
check = true;
}
// Checks if user enters a value that is not a double
catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a numeric value.");
input.nextLine();
if(debug == true)
e.printStackTrace();
}
}while(!check);
customerAccount = new Client(idNumber, startingBalance);
System.out.println("Please enter client's first name: ");
firstName = input.nextLine();
customerAccount.setFName(firstName);
// Verifies first name is only letters, either capital or lowercase
while(firstName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. First name needs to be all letters. Please try again.");
firstName = input.nextLine();
customerAccount.setFName(firstName);
}
System.out.println("Please enter client's last name: ");
lastName = input.nextLine();
customerAccount.setLName(lastName);
// Verifies last name is only letters, either capital or lowercase
while(lastName.matches("[a-zA-Z]*") == false) {
System.out.println("Invalid input. Last name needs to be all letters. Please try again.");
lastName = input.nextLine();
customerAccount.setLName(lastName);
}
System.out.println("Please enter client's email address: ");
emailAddress = input.nextLine();
customerAccount.setEmail(emailAddress);
// Verifies email address only uses lowercase/capital letters, dot, underscore, and/or dashes followed by # symbol to specify domain
while(emailAddress.matches("^[A-Za-z0-9+_.-]+#(.+)$") == false) {
System.out.println("Invalid input. Email not in valid format. Please try again.");
emailAddress = input.nextLine();
customerAccount.setEmail(emailAddress);
}
System.out.println("Please enter client's phone number: ");
phoneNumber = input.nextLine();
// Verifies phone number follows valid North American format 000-000-0000
while(phoneNumber.matches("[0-9]\\d{2}-[0-9]\\d{2}-\\d{4}") == false) {
System.out.println("Invalid input. Phone number must be in the following format: 123-456-7890. Please try again.");
phoneNumber = input.nextLine();
customerAccount.setPNumber(phoneNumber);
}
// Verifies that the starting balance the user inputs is positive
while(startingBalance < 0) {
System.out.println("**********************************");
System.out.println("ERROR: You can not start with a negative balance.");
System.out.println("Please enter a POSITIVE value for your starting balance: ");
startingBalance = input.nextDouble();
}
}//end switch
}
// Debugging to verify user input is correctly stored
if(debug == true) {
System.out.println(customerAccount.toString());
Account testing = customerAccount.getAccount();
System.out.println("ID: "+testing.getID()+ " Balance: "+testing.getBalance());
}
System.out.println("********************************");
System.out.println("Your account has been fully initialized! Thank you for choosing Java World Bank!");
System.out.println("********************************");
// Loops through menu prompt until user enters 4 to quit
int choice = 0;
while(choice != 4) {
System.out.println("Client Menu");
System.out.println("[1] Check Balance");
System.out.println("[2] Withdraw");
System.out.println("[3] Deposit");
System.out.println("[4] Exit");
System.out.println("=================================");
// Continiously prompts user to enter valid input
check = false;
do {
try {
System.out.println("So... What do you want to do?");
choice = input.nextInt();
check = true;
}
// Checks if user enters an unexpected input (not a digit)
catch(InputMismatchException e) {
System.out.println("Invalid input! Please use a numeric value between 1 and 4.");
if(debug == true)
e.printStackTrace();
input.nextLine();
}
}while(!check);
double amount = 0;
switch(choice) {
// Will display updated balance
case 1:
System.out.println("Your current balance is: $"+customerAccount.getAccount().getBalance());
System.out.println("********************************");
break;
// Allows user to withdraw money from current balance
case 2:
// Continiously prompts user to enter valid input
check = false;
do {
try {
System.out.println("How much do you wish to withdraw?");
amount = input.nextDouble();
customerAccount.getAccount().withdraw(amount); // Passes withdraw value to Account class
System.out.println("********************************");
check = true;
}
// Validates that customer has enough money to withdraw the specified amount
catch(OutOfMoney error) {
System.out.println("You do not have enough funds to do this.");
System.out.println("********************************");
}
// Validates that customer enters expected input
catch(InputMismatchException e) {
System.out.println("INVALID INPUT. Please enter a numeric value.");
// Used to clear input buffer after catching exception
input.nextLine();
System.out.println("********************************");
}
}while(!check);
// Debugging to make sure values are correctly calculated
if(debug == true)
System.out.println(customerAccount.getAccount().getBalance());
break;
// Allows user to deposit money to current balance
case 3:
check = false;
do {
try {
System.out.println("How much do you wish to deposit?");
amount = input.nextDouble();
customerAccount.getAccount().deposit(amount); // Passes deposit value to Account class
System.out.println("********************************");
check = true;
}
// Validates that user enters expected input
catch(InputMismatchException e) {
System.out.println("Invalid input. Please enter a numeric value.");
// Used to clear input buffer after catching exception
input.nextLine();
System.out.println("********************************");
}
}while(!check);
// Debugging to make sure values are correctly calculated
if(debug == true)
System.out.println(customerAccount.getAccount().getBalance());
break;
// Exits program
case 4:
System.out.println("Thank you for choosing Java World Bank!");
break;
// Checks if user does not enter 1, 2, 3, or 4 in main menu prompt
default:
System.out.println("You have entered an invalid input. Please try again.");
System.out.println("********************************");
break;
}
}
input.close();
}
}
Since the initialization of your object happens in a condition the compiler cannot figure out if it is initialized or not so you need to make sure its initialized outside a condition,for example make it null.
Client customerAccount = null ;
First, you may want to see here about declaring and initializing variables: here
You initialize the customerAccount on this line: customerAccount = new Client(idNumber, startingBalance);
However, that occurs within the switch in case 4. Then on this line System.out.println(customerAccount.toString()); you attempt to access the customerAccount's toString function. As this step is not in case 4, customerAccount may not be initialized.
Consider the case where the switch statement does not go to 4 and debug is set to true. customerAccount will be declared from this line: Client customerAccount; however, the code path will not initialize it in any way so you cannot call toString on it.
One solution could be to initialize the customerAccount to a null when you declare it or to a new Client(), or only attempt to access this variable after it was necessarily initialized. Hard to be sure without seeing the Client class.
Do note that in the null case, you may have to do some null checks, for instance, if customerAccount is null then customerAccount.toString() will throw an exception.

My Code won't stop printing in a loop

import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank
{
double balance = 0;
double amount = 0;
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
//Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
//balance = amount + balance;
break;
case 2:
//Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch(InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
//balance = balance - amount;
break;
case 3:
//check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println(account1.balance);
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while
(!quit);
}
}
My code otherwise works fine but I can't seem to figure out why it won't stop repeatedly printing my error message for the user. If someone can point out my error for me that would be fantastic. I did have this same code in another question however they fixed my problem that I had in the last question and were unable to answer the problem that arose here.
You need to remove or comment out the following line from your code :
in.useDelimiter("\n");
This is causing the the character "\n" to be passed to the amount = in.nextDouble(), which in turn causes the InputMismatchException to be thrown , thus resulting in an infinite loop.
UPDATE : Working code and the Sample output for your convinience:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Bank {
public static void main(String[] args) {
double balance = 0;
double amount = 0;
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
int userChoice;
BankAccount account1 = new BankAccount();
boolean quit = false;
{
do {
System.out.println("Your Choice: ");
System.out.println("For Deposit type 1");
System.out.println("For Withdraw type 2");
System.out.println("For Check Balance type 3");
System.out.println("Type 0 to quit");
System.out.print("User Input :");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
// Deposit Money
boolean inputInvalid = false;
do {
System.out.println("How Much would you like to deposit?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
inputInvalid = true;
}
} while (inputInvalid);
System.out.println("Depositing: " + amount);
account1.deposit(amount);
// balance = amount + balance;
break;
case 2:
// Withdraw money
boolean InvalidInput = false;
do {
System.out.println("How Much would you like to withdraw?");
try {
// in.useDelimiter("\n");
amount = in.nextDouble();
InvalidInput = false;
} catch (InputMismatchException ime) {
System.out.println("Invalid input. Try Again");
InvalidInput = true;
}
} while (InvalidInput);
System.out.println("Withdrawing: " + amount);
account1.withdraw(amount);
// balance = balance - amount;
break;
case 3:
// check balance
System.out.println("Checking Balance.");
account1.getBalance();
System.out.println("Available Balance is : " + account1.getBalance());
break;
case 0:
System.out.println("Thanks for Using BankAccount Banking System!");
quit = true;
break;
default:
System.out.println("Error: Choice not recognized please choose again.");
continue;
}
if (userChoice == 0)
quit = true;
} while (!quit);
}
}
}
Sample Output :
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :1
How Much would you like to deposit?
100
Depositing: 100.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :25
Error: Choice not recognized please choose again.
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :2
How Much would you like to withdraw?
25
Withdrawing: 25.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :3
Checking Balance.
Available Balance is : 75.0
Your Choice:
For Deposit type 1
For Withdraw type 2
For Check Balance type 3
Type 0 to quit
User Input :0
Thanks for Using BankAccount Banking System!
Try this
String value = in.nextLine();
String v="";
for(int i=0;i<value.length();i++)
if(value.charAt(i)!='\n')
v+=value.charAt(i);
double amount =-1;
if(v!=null)
amount = Double.parseDouble(v);

How to go back to the "try" code everytime the input is not correct (in Java)?

I want the program to retry the "try" part of the code every time the input is incorrect and throws an error(which is solved with an exception).
My code looks like this:
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
}catch(Exception e){
System.out.println("Incorrect input!");
My "makeHumanMove" function checks, if the number is from 1 to 3.. But if the user inserts a letter, it would throw an error and if it happens, I want the program to ask for another input until the user inserts a correct input.
I've tried while and for loops but I keep messing up. Any ideas?
How's about this code:
while (true) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
break;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Make sure that your makeHumanMove(enteredNumber); throws new Exception();
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
inputIsCorrect = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
This, of course, assumes that your makeHumanMove method throws an exception.
If I was doing this, I don't think I would be using exceptions. My code would be more like ...
boolean inputIsCorrect = false;
while(inputIsCorrect == false){
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
inputIsCorrect = makeHumanMove(enteredNumber);
}
I'd change the makeHumanMove return a value that indicates whether the the inout is valid or not, rather than using exceptions. ( Can't remember if scanner.nextInt() throws exception .... )
Use a boolean value outside, set it to true at the end of the try block. Then you can test for it using a while loop.
int enteredNumber;
boolean correctNumber = false;
while (!correctNumber) {
try {
System.out.print("Enter a number from 1 to 3: ");
enteredNumber = userInputScanner.nextInt();
makeHumanMove(enteredNumber);
correctNumber = true;
}catch(Exception e){
System.out.println("Incorrect input!");
}
}
Note that you should not use exceptions at all to report incorrect input. You should test for incorrect input and abort early. You should also consider if makeHumanMove should actually be part of the try/catch block; input validation should not be part of the business logic of your application.
final int number;
System.out.print("Enter a number from 1 to 3: ");
while (true) {
int enteredNumber;
try {
enteredNumber = userInputScanner.nextInt();
} catch (Exception e) {
System.out.print("Not a number, enter a number from 1 to 3: ");
userInputScanner = new Scanner(System.in);
continue;
}
if (enteredNumber < 1 || enteredNumber > 3) {
System.out.print("Incorrect number, enter a number from 1 to 3: ");
continue;
} else {
number = enteredNumber;
break;
}
}
makeHumanMove(number);

How do i make the program keep looping until the user has entered an integer

i am trying to modify my program so that even when the user has entered a string instead of the program crashing it should keep looping and asking for the user to enter the exam grade which needs to be an integer, only when the user has entered an integer should the program terminate. I am referring to the code in the do-while block
import java.util.InputMismatchException;
import java.util.Scanner;
public class CatchingException {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score;
String choice;
try {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
do {
if(score <40) {
System.out.println("You FAILED");
}else if(score >=40 && score <50){
System.out.println("Your grade: PASS MARK");
}else if(score >=50 && score <60) {
System.out.println("Your grade: 2:2");
}else if (score >=60 && score <70) {
System.out.println("Your grade: 2:1");
}else {
System.out.println("Your grade: 1:1");
}
System.out.println("Do you want to enter another grade: ");
choice = scan.next();
if(choice.equalsIgnoreCase("yes")) {
System.out.println("Enter your percentage mark: ");
score = scan.nextInt();
System.err.println("Incorrect Input");
}
}while();
}catch(InputMismatchException e) {
System.err.println("Incorrect Input ");
}
System.out.println("program terminated");
scan.close();
}
}
Use a boolean variable to keep track of whether or not to keep looping. For example:
boolean loop = true;
do {
// set loop to false when you want to end
} while(loop);
so you could do:
int score = null;
boolean isInt = false;
do {
System.out.println("Enter your percentage mark:");
try {
score = scan.nextInt();
isInt = true;
} catch (InputMismatchException e) {
//Not An Integer
isInt = false;
}
} while(false)
//Do you if statements here if it gets out of the while loop which means the user entered an int
Instead of assuming the number inputed is an int, you can input it as a String and loop until that string represents an int:
int intScore;
String score;
boolean gotInt = false;
while (!gotInt) {
score = scan.next();
try {
intScore = Integer.valueOf(score);
gotInt = true;
} catch (NumberFormatException e) {
// output some warning
}
}
Did you consider using JOptionPane to get an input from the user? It is able to display a little window with a text field and a OK and Cancel button which would fit your needs perfectly.
Here is the documentation for JOptionPane#showInputDialog:
static String showInputDialog(Component parentComponent, Object message, String title, int messageType)
Shows a dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.

Categories

Resources