Object not Being Initialized Due to Scope - java

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.

Related

Scanner input with exception handling in a try/catch is not working like intended

I am making an atm program that takes in an account number and a pin. When I try to type in anything except the accepted accounts and pins that are predetermined, it is supposed to give an error message and the user tries again. The only problem is that it prints out the error message but moves on to the next input instead of repeating the previous input. i.e. goes from entering the account number to entering the pin number. The same thing happens for the pin as well. I really don't know what to make of it. Thanks in advance! Here's a snippet of my code:
import java.util.*;
import java.lang.*;
public class Menu {
Scanner input = new Scanner(System.in);
//Bank bank = new Bank();
boolean keepGoing = true;
public static void main(String[] args){
Menu menu = new Menu();
menu.startMenu();
}//end main
public void startMenu(){
int choice = 0;
int verify1 = 0;
int verify2 = 0;
int account = 0;
int pin = 0;
printGreet();
while(keepGoing){
System.out.print("Please enter Account number: ");
do{
try{
account = input.nextInt();
}//end try
catch(NumberFormatException e){
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();//clear buffer
}//end catch
catch(InputMismatchException e){
System.out.print("Error: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();//clear buffer
}//end catch
if(account < 0 || account > 99999){
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
//input.nextLine();//clear buffer
}//end if
}while(!(account >= 0 && account <= 99999));//end do/while
System.out.print("Please enter PIN number: ");
do{
try{
pin = input.nextInt();
}//end try
catch(NumberFormatException e){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();//clear buffer
}//end catch
catch(InputMismatchException e){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();//clear buffer
}//end catch
if(pin < 0 || pin > 99999){
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
//input.nextLine();//clear buffer
}//end if
}while(!(pin >= 0 && pin <= 99999));//end do/while
verify1 = verifyAccount(account);
verify2 = verifyPin(pin);
if((verify1 == 1) && (verify2 == 1)){
printAdminMenu();
choice = getAdminChoice();
adminChoices(choice);
}else if((verify1 == 2) && (verify2 == 2)){
printUserMenu();
choice = getUserChoice();
userChoices(choice);
}else{
System.out.println("ERROR: YOU ARE NOT AN AUTHORIZED USER...GOODBYE");
System.exit(0);
}//end if/else
}//end while
}//end startMenu()
The whiles only check if the account number is invalid. When a parsing error occurs the account/pin variable is still 0 so it doesn't repeat.
I fixed/improved the code for you. Note you should always debug your code before you ask a question on StackOverflow.
public void startMenu() {
int account = 0;
int pin = 0;
printGreet();
while (keepGoing) {
System.out.print("Please enter Account number: ");
boolean invalid;
do {
invalid = false;
try {
account = input.nextInt();
// Cancel if the number is invalid
if (account < 0 || account > 99999) {
throw new NumberFormatException();
}
} catch (NumberFormatException | InputMismatchException e) {
System.out.print("ERROR: That is not a valid account number. Please enter a valid account number (#####): ");
input.nextLine();
// Mark the loop iteration as invalid
invalid = true;
}
} while (invalid);
System.out.print("Please enter PIN number: ");
do {
invalid = false;
try {
pin = input.nextInt();
// Cancel if the number is invalid
if (pin < 0 || pin > 99999) {
throw new NumberFormatException();
}
} catch (NumberFormatException | InputMismatchException e) {
System.out.print("ERROR: That is not a valid pin number. Please enter a valid pin number (#####): ");
input.nextLine();
invalid = true;
}
} while (invalid);
verify1 = verifyAccount(account);
verify2 = verifyPin(pin);
if ((verify1 == 1) && (verify2 == 1)) {
printAdminMenu();
choice = getAdminChoice();
adminChoices(choice);
} else if ((verify1 == 2) && (verify2 == 2)) {
printUserMenu();
choice = getUserChoice();
userChoices(choice);
} else {
System.out.println("ERROR: YOU ARE NOT AN AUTHORIZED USER...GOODBYE");
System.exit(0);
}
}
}

Getting IllegalStateException in my program?

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.

How would I go about creating input commands to execute different part of my code? - Java

I have created a basic java program that determines the hypotenuse of a triangle. Originally, the program would ask for side A, then side B, and automatically calculate the hypotenuse.
I want to create a input command list that will allow the user to type "a" in when giving the A side value, type "b" when giving the B side value, and then type "c" to calculate the hypotenuse, or "q" to exit the program.
Instead of forcing the user to put in side A first, I want them to be able to put in either side at there will. However, if the user types "c" and either the A or B value is missing (or both) I would like an error message and have the user correct it.
So far I have
import java.util.InputMismatchException;
import java.util.Scanner;
public class handleExceptions1 {
public static void main(String[] args) {
Scanner initial = new Scanner(System.in);
System.out.println(" Type 'a' to enter the value for side A.\n Type 'b' to enter the value for side B.\n Type 'c' to calculate the hypotenuse.\n Or type 'q' to exit");
String inputselected = initial.next();
boolean repeat = true;
double _sideA = 0;
while (repeat) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter side A, this may not be 0: ");
_sideA = input.nextDouble();
if (_sideA > 0){
repeat = false;
}
} catch (InputMismatchException e) {
System.out.print("Error! Please enter a valid number!");
}
}
boolean repeat2= true;
double _sideB = 0;
while (repeat2){
try {
Scanner input = new Scanner(System.in);
System.out.print("Please enter side B, this may not be 0: ");
_sideB = input.nextDouble();
if (_sideB > 0){
repeat2= false;
}
} catch (InputMismatchException e) {
System.out.print("Error! Please enter a valid number!");
}
}
double hypotenuse = Math.sqrt((_sideA*_sideA) + (_sideB*_sideB));
System.out.print("Side C(the hypotenuse) is: "+ hypotenuse);
}
}
My logic is to put something after "String inputselected = ..." but I'm not sure what. If anyone can help me, it would be greatly appreciated !
sideA = -1;
sideB = -1;
Scanner input = new Scanner(System.in);
do
{
System.out.println("Enter your choice ( a/b/c/q ) : ");
char ch = in.nextChar();
switch(ch)
{
case 'a': sideA = in.nextDouble();
if(sideA<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'b': sideB = in.nextDouble();
if(sideB<0)
System.out.println("Error! Please enter a valid number!");
break;
case 'c': if(sideA<0 || sideB<0)
System.out.println("Other two sides not yet given! please provide a and b first. ");
else
System.out.print("Side C(the hypotenuse) is: "+ Math.sqrt((_sideA*_sideA) + (_sideB*_sideB)););
break;
case 'q': break;
default : System.out.println(" Enter a valid choice! ");
}
}while(ch!='q');

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.

while() loop for user input

I'm working on setting up a while() that executes until the user enters an integer. However, the way I have it now, the loop prints the message "Please enter an integer" again after the integer has been entered, and then the program executes normally. Can someone suggest a way to make not print that message again after an integer has been entered? Thanks!
System.out.println("Enter word length");
if(in.hasNextInt())
{
n = in.nextInt();
}
else
{
while(in.hasNext()) //this is the loop i'm talking about
{
System.out.println("Please enter an integer");
if(in.hasNextInt())
{
n = in.nextInt();
break;
}
else
{
String c = in.next();
}
}
}
I am assuming that you want user to enter int (or Integer) and repeatedly ask user until user enters int(or Integer). If so, try this:
System.out.println("Enter word length");
if(in.hasNextInt()) {
n = in.nextInt();
} else {
while(in.hasNext()) //this is the loop i'm talking about
{
if(in.hasNextInt())
{
n = in.nextInt();
break;
}
else
{
String c = in.next();
System.out.println("Please enter an integer");
}
}
}

Categories

Resources