Java if else with nested loop - java

I am having some problem with my java assignment and currently am stuck at the nested if else statement.I am actually trying to get an input age from the user and store in as a variable.After executing my code i am getting error when i run the program.Am i doing this correctly or is there some other way to program this?
Error message that i got
Enter your selection:
1
You have selected No.1
Please enter your age**Exception in thread "main"
java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Assignment.main(Assignment.java:48)**
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println(
"1. Add player" + "\n" +
"2.Display transaction" + "\n" +
"3.Begin the ride");
System.out.println("");
System.out.println("Enter your selection: ");
char selection = sc.findInLine(".").charAt(0);
sc.close();
switch(selection) {
case '1' :
System.out.println("You have selected No.1");
break;
case '2' :
System.out.println("You have selected No.2" );
break;
case '3' :
System.out.println("You have selected No.3" );
break;
default:
System.out.println("Please make a selection");
break;
}
if (selection=='1') {
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt();
while (age<100) {
age+=age;
}
}
else if (selection=='2') {
System.out.println("Display daily transaction");
}
else if (selection=='3') {
System.out.println("Begin the ride");
}
else {
System.out.println("Please enter a valid input");
}
}

Please read basic Java so that you can learn programs better.

you can reduce this code to a very good extent, i haven't removed nested-if statements, which you can by moving all execution under case statements.
This program will terminate if option entered is not a number, this can also be improved by reading it as a string and checking is its one of the valid options (map's key set).
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class SwitchCase {
public static Map<Integer, String> options = new LinkedHashMap<Integer, String>();
static {
options.put(1, "Add player");
options.put(2, "Display transaction");
options.put(3, "Begin the ride");
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
for (Integer option : options.keySet()) {
System.out.println(option + ". " + options.get(option));
}
System.out.println("Enter your selection: ");
int selection = sc.nextInt();
switch (selection) {
case 1:
case 2:
case 3:
System.out.println("You have selected No." + selection);
break;
default:
System.out.println("Please make a selection");
break;
}
if (selection == 1) {
int age = 0;
System.out.print("Please enter your age : ");
age = sc.nextInt();
while (age < 100) {
age += age;
}
System.out.println(age);
} else if (selection == 2) {
System.out.println(options.get(selection));
} else if (selection == 3) {
System.out.println(options.get(selection));
} else {
System.out.println("Please enter a valid input!");
}
}
}

switch case is a type of nested if else.we can use switch in place of nested if else.you need not to use both switch case and nested if else simultaneously.
you can write your code like this.
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("1. Add player" + "\n" +
"2.Display transaction" + "\n" +
"3.Begin the ride");
System.out.println("");
System.out.println("Enter your selection: ");
char selection = sc.findInLine(".").charAt(0);
switch(selection) {
case '1' :
System.out.println("You have selected No.1");
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt();
while (age<100) {
age+=age;
}
System.out.print(age);
break;
case '2' :
System.out.println("You have selected No.2" );
System.out.println("Display daily transaction");
break;
case '3' :
System.out.println("You have selected No.3" );
System.out.println("Begin the ride");
break;
default:
System.out.println("Please make a selection");
System.out.println("Please enter a valid input");
break;
}
sc.close();
}

The exception is pretty clear on the problem: java.lang.IllegalStateException: Scanner closed
Before your code enters the switch, you're closing the scanner with sc.close();. But later on you're trying to read from it again:
if (selection=='1') {
int age=0;
System.out.print("Please enter your age");
age = sc.nextInt(); // <---- Here
while (age<100) {
age+=age;
}
}
But this will fail if the scanner is already closed. To solve this, you can simply put the line sc.close() to the end of your main.
As an alternative you could wrap everything into a try-with-resources block, so that you don't have to care about closing the scanner anymore because it will be closed automatically after leaving the block.

Related

Switch cases are not getting executed properly

case 1 and default cases are not working properly print statement is not getting executed. I'm unable to identify the error. I don't know if there is problem with the scanner implementation it seems fine to me.
import java.util.*;
public class StartApp {
public static void main(String[] args) {
try {
String categoryName="";
int ch=0;
Scanner sc1=new Scanner(System.in);
Scanner sc2=new Scanner(System.in);
Logger.getInstance().log("Starting task manager", 1);
while(ch!=7)
{
System.out.println("press 1 to create category");
System.out.println("press 2 to load category");
System.out.println("press 3 to remove catergory");
System.out.println("press 4 to list category");
System.out.println("press 5 to search category");
System.out.println("press 6 to export");
System.out.println("press 7 to exit");
ch=sc1.nextInt();
}
switch(ch)
{
case 1:{
System.out.println("enter category name");
categoryName=sc2.nextLine();
sc2.nextLine();
while(!ProjectUtility.validateName(categoryName))
{
System.out.println("category name must be one word. It cannot contain a numbers,spaces and Alpanumerics.");
categoryName=sc2.nextLine();
}
break;}
case 7:
System.out.println("exiting...");
break;
default:
System.out.println("option not supported");
break;
}
}
catch(Throwable t)
{
t.printStackTrace();
}
}
}
You will only get out of your while loop if the condition while(ch!=7){...} turns false. So your switch label '7' is the only reachable in the whole switch. The Solution is to put your switch in your while loop.
You only need one Scanner and you should close it at the end
public static void main(String[] args) {
try {
String categoryName = "";
int ch = 0;
Scanner sc = new Scanner(System.in);
Logger.getInstance().log("Starting task manager", 1);
while (ch != 7) {
System.out.println("press 1 to create category");
System.out.println("press 2 to load category");
System.out.println("press 3 to remove catergory");
System.out.println("press 4 to list category");
System.out.println("press 5 to search category");
System.out.println("press 6 to export");
System.out.println("press 7 to exit");
System.out.println();
System.out.print("input: ");
ch = sc.nextInt();
switch (ch) {
case 1: {
System.out.print("enter category name: ");
categoryName = sc.nextLine();
sc.nextLine();
while (!ProjectUtility.validateName(categoryName)) {
System.out.println("category name must be one word. It cannot contain a numbers,spaces and Alpanumerics.");
System.out.print("enter category name: ");
categoryName = sc.nextLine();
}
break;
}
case 7:
System.out.println("exiting...");
break;
default:
System.out.println("option not supported");
break;
}
}
sc.close();
} catch (Throwable t) {
t.printStackTrace();
}
}

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.

Java if statement after switch

I need help with a if statement.
What I want to do is after the default, put an if statement that basically says
if name equals Mike or lady
then print out "Type a number between 1-3 to see your prize".
And if you type for example 1, it should print out you won a Bicycle.
I know that not that many Pro-programmers use switch but that's all I know for now :)
import java.util.Scanner;
public class Ifwasif {
public static void main (String [] args) {
System.out.println("Welcome to our Store!");
System.out.println("we hope you will find what you're looking for");
Scanner input = new Scanner (System.in);
System.out.print("To check out, please type your name: ");
String name = input.nextLine();
System.out.print("You need to confirm your age, please type your age: ");
int age = input.nextInt();
Scanner input1 = new Scanner (System.in);
System.out.print("You have an award to collect! To collect it type your name: ");
String namee = input1.nextLine();
switch (namee) {
case ("Mike"):
System.out.println("Congrats, you are the Winner!");
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
case ("lady"):
System.out.println("Congrats, you are the Winner!");
break;
default:
System.out.println("Your name is not in the list!");
}
}
}
Rather than an if statement after the switch, combine your 2 "winner" cases into a single case:
switch (namee) {
case ("Mike"):
case ("lady"):
System.out.println("Congrats, you are the Winner!");
// insert code here to prompt for input, read result, compare, and award
// or put that code into a new method
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
default:
System.out.println("Your name is not in the list!");
Should work fine:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
System.out.println("Welcome to our Store!");
System.out.println("we hope you will find what you're looking for");
Scanner input = new Scanner(System.in);
System.out.print("To check out, please type your name: ");
String name = input.nextLine();
System.out.print("You need to confirm your age, please type your age: ");
int age = input.nextInt();// variable never used
input.nextLine();
System.out.print("You have an award to collect! To collect it type your name: ");
String namee = input.nextLine();
switch (namee) {
case ("Mike"):
case ("lady"):
System.out.println("Congrats, you are the Winner!");
break;
case ("Don"):
System.out.println("Sorry you are not the winner!Better luck next time");
break;
default:
System.out.println("Your name is not in the list!");
break;
}
if("Mike".equals(name) || "lady".equals(name)){
System.out.println("Type a number between 1-3 to see your prize'");
int number = input.nextInt();
switch (number) {
case 1:
System.out.println("You won a Bicycle");
break;
default:
break;
}
}
}
}

I'm having trouble with a java login menu app

I have a project in college to create a login menu type application.
I am very much a beginner so please bear with me.
Can I ask for someone to point me in the right direction as I've hit a bit of a blank on this one.
The application isn't finished so I understand there will be more that needs adding to it, just know that it is only a very barebones application I am looking to build.
After choosing option 1, the app tells the user to first change password and attempts. After changing the password and the attempts (I'm changing it to 5 when testing) and re-choosing option 1, this error comes up -
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - not a statement
at loginmenu.LoginMenu.loginAttempt(LoginMenu.java:74)
at loginmenu.LoginMenu.showMenu(LoginMenu.java:34)
at loginmenu.LoginMenu.loginAttempt(LoginMenu.java:77)
at loginmenu.LoginMenu.showMenu(LoginMenu.java:34)
at loginmenu.LoginMenu.main(LoginMenu.java:12)
Here is the code -
package loginmenu;
import java.util.Scanner;
public class LoginMenu {
private static String correctPassword;
public static String userPassword;
public static int attemptsCounter;
public static boolean loggedIn;
public static void main(String[] args) {
showMenu();
loginAttempt();
}
public static void showMenu()
// displays a menu and keeps displaying until user chooses the QUIT option
{
int userChoice;
Scanner myScan = new Scanner(System.in);
do {
System.out.println("1. Login");
System.out.println("2. Change Password");
System.out.println("3. Change Attempts");
System.out.println("4. Quit");
userChoice = myScan.nextInt();
switch (userChoice) {
case 1: {
System.out.println("You chose to login.");
loginAttempt();
break;
}
case 2: {
System.out.println("You chose to change password.");
Scanner myNewScan = new Scanner(System.in);
System.out.println("Please enter a password.");
userPassword = myNewScan.nextLine();
break;
}
case 3: {
System.out.println("You chose to change attempts.");
Scanner myNewScan = new Scanner(System.in);
System.out.println("Please enter amount of attempts.");
attemptsCounter = myNewScan.nextInt();
break;
}
case 4: {
System.out.println("You have quit the program.");
break;
}
default: {
System.out.println("Not a valid choice.");
}
}// closes switch
} while (userChoice != 4);
myScan.close();
System.out.println("Goodbye.");
}// closes showMenu1
public static void loginAttempt()
{
Scanner scan = new Scanner(System.in);
while (correctPassword != userPassword) && (attemptsCounter>=5);
{
System.out.println("Please change password and attempts first.");
showMenu();
}
if (userPassword == correctPassword) && (attemptsCounter<=5)
{
System.out.println("You entered the correct password in " + attemptsCounter + " attempts");
}
if (attemptsCounter>=6)
{
System.out.println("You have been locked out.");
}
}
}
Fix your brackets and ditch the semicolon and don't use ==/!= for strings.
while (correctPassword != userPassword) && (attemptsCounter>=5);
should be
while (!correctPassword.equals(userPassword) && (attemptsCounter>=5))
same issue with brackets here:
if (userPassword == correctPassword) && (attemptsCounter<=5)
This is my approach of your question.
First, i set the my password at the first place.
private static String correctPassword = "tommybee";
And, i can call the showMenu method only in this case.
public static void main(String[] args) {
showMenu();
}
You don't have to call the showMenu method in your loginAttempt and the while statement is also removed.
public static void loginAttempt() {
if (!(userPassword.toLowerCase().equals(correctPassword)) && (attemptsCounter >= 5)) {
System.out.println("Please change password and attempts first.");
}
if ((correctPassword.toLowerCase().equals(userPassword)) && (attemptsCounter <= 5)) {
System.out.println("You entered the correct password in " + attemptsCounter + " attempts");
}
if (attemptsCounter >= 6) {
System.out.println("You have been locked out.");
}
}
In the showMenu method, i use only one scanner class with system's input stream.
Check the scanner class.
Declare a Scanner class and initialize a userChoice variable to 4.
Scanner myScan = new Scanner(System.in);
int userChoice = 4;
Here is showMenu method.
public static void showMenu()
// displays a menu and keeps displaying until user chooses the QUIT option
{
Scanner myScan = new Scanner(System.in);
int userChoice = 4;
do {
System.out.println("Choose one of the list below");
System.out.println("1. Login");
System.out.println("2. Change Password");
System.out.println("3. Change Attempts");
System.out.println("4. Quit");
if(myScan.hasNextInt())
{
userChoice = myScan.nextInt();
switch (userChoice) {
case 1: {
System.out.println("You choose to login.");
System.out.println("Please enter a password.");
userPassword = myScan.next();
System.out.println("pass " + userPassword);
loginAttempt();
break;
}
case 2: {
System.out.println("You choose to change password.");
System.out.println("Please enter a new password.");
correctPassword = myScan.next();
break;
}
case 3: {
System.out.println("You choose to change attempts.");
System.out.println("Please enter amount of attempts.");
attemptsCounter = myScan.nextInt();
break;
}
case 4: {
System.out.println("You have quit the program.");
break;
}
default: {
System.out.println("Not a valid choice.");
}
}// closes switch
}
} while (myScan.hasNext() && userChoice != 4);
myScan.close();
System.out.println("Goodbye.");
}// closes showMenu1
I use a next method instead of a nextInt method.
See the next method of the api document.
This method may block while waiting for input to scan,
Here is what i have done.
import java.util.Scanner;
public class LoginMenu {
private static String correctPassword = "tommybee";
public static String userPassword;
public static int attemptsCounter;
public static boolean loggedIn;
public static void main(String[] args) {
showMenu();
//loginAttempt();
}
public static void showMenu()
// displays a menu and keeps displaying until user chooses the QUIT option
{
Scanner myScan = new Scanner(System.in);
int userChoice = 4;
do {
System.out.println("Choose one of the list below");
System.out.println("1. Login");
System.out.println("2. Change Password");
System.out.println("3. Change Attempts");
System.out.println("4. Quit");
if(myScan.hasNextInt())
{
userChoice = myScan.nextInt();
switch (userChoice) {
case 1: {
System.out.println("You choose to login.");
System.out.println("Please enter a password.");
//Scanner myNewScan = new Scanner(System.in);
userPassword = myScan.next();
//myNewScan.close();
System.out.println("pass " + userPassword);
loginAttempt();
break;
}
case 2: {
System.out.println("You choose to change password.");
//Scanner myNewScan = new Scanner(System.in);
System.out.println("Please enter a new password.");
correctPassword = myScan.next();
//myNewScan.close();
break;
}
case 3: {
System.out.println("You choose to change attempts.");
//Scanner myNewScan = new Scanner(System.in);
System.out.println("Please enter amount of attempts.");
attemptsCounter = myScan.nextInt();
//myNewScan.close();
break;
}
case 4: {
System.out.println("You have quit the program.");
break;
}
default: {
System.out.println("Not a valid choice.");
}
}// closes switch
}
} while (myScan.hasNext() && userChoice != 4);
myScan.close();
System.out.println("Goodbye.");
}// closes showMenu1
public static void loginAttempt() {
//while ((correctPassword != userPassword) && (attemptsCounter >= 5)) {
if (!(userPassword.toLowerCase().equals(correctPassword)) && (attemptsCounter >= 5)) {
System.out.println("Please change password and attempts first.");
//showMenu();
}
if ((correctPassword.toLowerCase().equals(userPassword)) && (attemptsCounter <= 5)) {
System.out.println("You entered the correct password in " + attemptsCounter + " attempts");
}
if (attemptsCounter >= 6) {
System.out.println("You have been locked out.");
}
}
}

Using Scanner inside a for loop for system input

I have been struggling with this for a while. I essentially want to loop through and read in as many strings as determined by num_choices. The following code only executes the else condition.
Scanner s2 = new Scanner(System.in);
for(int i=0; i < this.num_choices; i++)
{
if(s2.hasNext())
{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
}
else
{
System.out.println("Lets end this");
}
}
`
I am getting this: Exception in thread "main" java.util.NoSuchElementException. In the main class, this is where the error points to
choice2 = Integer.parseInt(read_choice2.next());
which is inside a while loop as well. Here is the code for that:
public class Main
{
public static void main(String args[]) throws IOException
{
Vector<Survey> mysurveys = new Vector<Survey>();
boolean carry_on = true;
int choice = 0;
Scanner read_choice = new Scanner(System.in);
System.out.println("Let's begin the Survey/Test application!");
while(carry_on)
{
System.out.println("What would you like to do?");
System.out.println("1. Create a new Survey");
System.out.println("2. Create a new Test");
System.out.println("3. Display a Survey");
System.out.println("4. Display a Test");
System.out.println("5. Save a Survey");
System.out.println("6. Save a Test");
System.out.println("7. Load a Survey");
System.out.println("8. Load a Test");
System.out.println("9. Quit");
System.out.println();
System.out.println("Please enter a number for the operation you want to perform: ");
choice = Integer.parseInt(read_choice.next());
/*try
{
choice = Integer.parseInt(buffer.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice.nextInt();
}*/
switch(choice)
{
case 1:
System.out.println("Please Enter a Name for your Survey");
String in = buffer.readLine();
Survey s1 = new Survey();
s1.CreateNew(in);
mysurveys.add(s1);
////
add_question(s1.type);
break;
case 2:
System.out.println("Please Enter a Name for your Test");
//String in = buffer.readLine();
Test t1 = new Test();
//t1.CreateNew(in);
mysurveys.add(t1);
break;
////
//add_question(t1.type);
case 3:
break;
// call Survey.display()
case 4:
break;
case 5:
Survey s = new Survey();
ReadWriteFiles x = new ReadWriteFiles();
x.SaveSurvey(s);
break;
case 6:
Test t = new Test();
//ReadWriteFiles x = new ReadWriteFiles();
//x.SaveSurvey(t);
break;
case 7:
carry_on = false;
break;
default:
System.out.println("Incorrect Input. Try Again");
System.out.println();
break;
}
}
read_choice.close();
}
public static void add_question(String type) throws IOException, NullPointerException
{
Questions q = null;
boolean carry_on2 = true;
int choice2 = 0;
Scanner read_choice2 = new Scanner(System.in);
//BufferedReader buffer2=new BufferedReader(new InputStreamReader(System.in));
while (carry_on2)
{
//
System.out.println("1. Add a new T/F Question");
System.out.println("2. Add a new Multiple Choice Question");
System.out.println("3. Add a new Short Answer Question");
System.out.println("4. Add a new Essay Question");
System.out.println("5. Add a new Ranking Question");
System.out.println("6. Add a new Matching Question");
System.out.println("7. If you want to stop adding more questions, and go back to the main menu.");
System.out.println("Please enter a number for the operation you want to perform: ");
choice2 = Integer.parseInt(read_choice2.next());
/*try
{
choice2 = Integer.parseInt(buffer2.readLine());
}
catch(InputMismatchException e)
{
System.out.println("Invalid input. Please Enter again.");
System.out.println();
//read_choice2.nextInt();
}*/
switch(choice2)
{
case 1:
q = new TrueFalse();
break;
case 2:
q = new MultipleChoice();
break;
case 3:
q = new ShortAnswer();
break;
case 4:
q = new Essay();
break;
case 5:
q = new Ranking();
break;
case 6:
q = new Matching();
break;
case 7:
carry_on2 = false;
break;
default:
System.out.println("Incorrect Input.");
break;
}
q.createQuestion(type);
}
}
}
I realize there is a lot of messy code, and I apologize for that. I just wanted to show the entire thing, so it's easier to spot the problem. Help would be appreciated.
In general way, you should add if(read_choice.hasNext()) before invoking read_choice.next(); You have the exception java.util.NoSuchElementException because no elements found to be read. this is a good habit.
About your problem, you are getting error because you has closed scanner before finish reading. Put read_choice.close() outside of loop.
Moreover, for simplify, if you want to read integer, just simple : scanner.nextInt().
read_choice.close();
Don't close the scanner as long as you are not done reading all the inputs. Doing also closes the underlying input stream (System.in), check the documention;
You don't need to initialize the Scanner multiple times. Just create one instance and pass it around (keep using it).
Also,
for(int i=0; i < this.num_choices; i++)
{
//if(s2.hasNext())
//{
System.out.println("Enter choice " + (i+1) +":");
String ch = s2.next();
//this.choices.addElement(ch);
you don't need that condition check. The next() will block until the input is entered.

Categories

Resources