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.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have a problem because I do not know how to save the variable. The variable newname and the newpassword deafult are zero. But in case 1 they are changed to the given values, but after case 1 the variables return to the basic values 0. and i cant log in (in case 2) becasue login and password always are 0. How i can globally set this variable on case 1?
String newname = null;
String newpassword = null;
System.out.println("Hello!");
System.out.println();
System.out.println(" ****************************************");
System.out.println(" * MENU *");
System.out.println(" ****************************************");
System.out.println(" 1. Create new account");
System.out.println(" 2. Log in");
System.out.println(" 3. Help");
System.out.println(" 0. End");
Scanner opcje = new Scanner(System.in);
int choose = opcje.nextInt();
switch (choose) {
case 1:
System.out.println("You choose create new acount\n Enter the login");
Scanner nlogin = new Scanner(System.in);
newname = nlogin.nextLine();
System.out.println("Please enter the password ");
Scanner npassword = new Scanner(System.in);
newpassword = npassword.nextLine();
System.out.println("the account has been created\n");
case 2:
Scanner login = new Scanner(System.in);
System.out.println("Login:");
String pass1 = login.nextLine();
System.out.println("Password:");
Scanner password = new Scanner(System.in);
String pass2 = password.nextLine();
if (pass1 == newname & pass2 == newpassword){
System.out.println("you are logged in");
}else{
System.out.println("incorrect passoword or login");
}
break;
case 3:
System.out.println("Help is off");
break;
case 0:
System.out.println("ending");
break;
default:
System.out.println("Select the option by pressing 1,2,3 or 0");
break;
}
}
}
One of the problems is with this line:
if (pass1 == newname & pass2 == newpassword){
System.out.println("you are logged in");
}else{
System.out.println("incorrect passoword or login");
}
If you will debug this code, You will notice that this if statement, doesn't
compare the values of the String. For more details you may visit:
https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
Try this code instead:
if(pass1.equals(newname) && pass2.equals(newpassword))
{
System.out.println("you are logged in");
}else{
System.out.println("incorrect passoword or login");
}
second problem:
you need to put your switch statement in a while loop:
1.This why the program won't end (and this way the variable) will be saved.
2.IF the user input is invalid instead of going to default, the program will also ask again for the user to write a number.
There are so many issues here.
You are missing a break; after the first case
You potentially have a scope issue for your variables if they are simply local variables in the method and you call the method repeatedly then their contents are simply forgotten in between calls.
You are comparing Strings using == , Read More here => Java String Equals
Correct Code:
public class MainClass {
String newname = null;
String newpassword = null;
//continue your code here
//call menu() when required
menu();
}
public void menu()
{
System.out.println("Hello!");
System.out.println();
System.out.println(" ****************************************");
System.out.println(" * MENU *");
System.out.println(" ****************************************");
System.out.println(" 1. Create new account");
System.out.println(" 2. Log in");
System.out.println(" 3. Help");
System.out.println(" 0. End");
Scanner opcje = new Scanner(System.in);
int choose = opcje.nextInt();
switch (choose)
{
case 1:
System.out.println("You choose create new acount\n Enter the login");
Scanner nlogin = new Scanner(System.in);
newname = nlogin.nextLine();
System.out.println("Please enter the password ");
Scanner npassword = new Scanner(System.in);
newpassword = npassword.nextLine();
System.out.println("the account has been created\n");
break;
case 2:
Scanner login = new Scanner(System.in);
System.out.println("Login:");
String pass1 = login.nextLine();
System.out.println("Password:");
Scanner password = new Scanner(System.in);
String pass2 = password.nextLine();
if (pass1.equals(newname) & pass2.equals(newpassword)){
System.out.println("you are logged in");
}else{
System.out.println("incorrect password or login");
}
break;
case 3:
System.out.println("Help is off");
break;
case 0:
System.out.println("ending");
break;
default:
System.out.println("Select the option by pressing 1,2,3 or 0");
break;
}
}
Try changing the way you compare Strings, also use java logical operators instead of Bitwise &.
static String newname = null;
static String newpassword = null;
public static void main(String[] args) {
System.out.println("Hello!");
System.out.println();
System.out.println(" ****************************************");
System.out.println(" * MENU *");
System.out.println(" ****************************************");
System.out.println(" 1. Create new account");
System.out.println(" 2. Log in");
System.out.println(" 3. Help");
System.out.println(" 0. End");
Scanner opcje = new Scanner(System.in);
int choose = opcje.nextInt();
switch (choose) {
case 1:
System.out.println("You choose create new acount\n Enter the login");
Scanner nlogin = new Scanner(System.in);
newname = nlogin.nextLine();
System.out.println("Please enter the password ");
Scanner npassword = new Scanner(System.in);
newpassword = npassword.nextLine();
System.out.println("the account has been created\n");
case 2:
Scanner login = new Scanner(System.in);
System.out.println("Login:");
String pass1 = login.nextLine();
System.out.println("Password:");
Scanner password = new Scanner(System.in);
String pass2 = password.nextLine();
//Java uses equals method to compare Strings
//Java also uses && as the logical operator for "and"
if (pass1.equals(newname) && pass2.equals(newpassword)) {
System.out.println("you are logged in");
} else {
System.out.println("incorrect password or login");
}
break;
case 3:
System.out.println("Help is off");
break;
case 0:
System.out.println("ending");
break;
default:
System.out.println("Select the option by pressing 1,2,3 or 0");
break;
}
}
I'm trying to code simple calculator (all in one) using Switch cases in java. I came up with following code so far. However I'm stuck with while loop. I want to keep showing main menu after each case execution until user decides to exit the program.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result=0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is "+result);
}
}
Above code works fine. Program ends itself after execution of user selected choice. I want to put main menu on a repeat.
Add a while loop like this:
public static void main(String[] args) {
// Moved this outside the while loop as davidxxx pointed out +1
Scanner s = new Scanner(System.in);
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i = s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;//'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
System.out.println("Wrong Choice.");
}
System.out.println("Answer is " + result);
System.out.println("Go again?");
String goAgain = s.next();
if (!goAgain.equals("y")) {
break;
}
}
}
Try this:
import java.util.Scanner;
public class Calculator {
private static final String EXIT = "EXIT";
public static void main(String[] args) {
Calculator calc = new Calculator();
Scanner s = new Scanner(System.in);
while (true) {
String res = calc.runCalc(s);
if (res.equals(EXIT)) {
break;
} else {
System.out.println(res);
}
}
}
private String runCalc(Scanner s) {
System.out.println("Main Menu:");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.println("Enter your choice: ");
int i = s.nextInt();
if (i == 5) {
return EXIT;
}
System.out.println("ENTER FIRST NUMBER ");
int a = s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b = s.nextInt();
int result = 0;// 'result' will store the result of operation
switch (i) {
case 1:
result = a + b;
break;
case 2:
result = a - b;
break;
case 3:
result = a * b;
break;
case 4:
result = a / b;
break;
default:
return "Wrong Choice.";
}
return "Answer is " + result;
}
}
There is more than one way to achieve this, you can use
while loop.
do-while loop.
for loop.
I think do-while loop is better for your situation. Because either user wants to continue or not you have to proceed one time(before loop false). And you do not want to use another variable for quit the loop.
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int result=0;
do{
System.out.println("Main Menu:");
System.out.println("-1. complete and calculate");
System.out.println("1. Addition");
System.out.println("2. Substraction");
System.out.println("3. Multipication");
System.out.println("4. Division");
System.out.println("Enter your choice: ");
int i=s.nextInt();
if(i ==-1){
System.out.println("Answer is "+result);
return;
}
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
case 3:
result=a*b;
break;
case 4:
result=a/b;
break;
default:
System.out.println("Wrong Choice.");
break;
}
}while(true);
}
On my previous question I've learned that I shouldn't close the System.in, and I also learned that using multiple Scanner together can cause problems.
The problem is that I need some methods recursively to use the Scanner to scan some inputs from the user.
Example
public void usersChoice(){
int choice = 0;
while(true){
try{
Scanner scan = new Scanner(System.in);
System.out.print("Choose an option: ");
choice = scan.nextInt();
break;
}
catch(Exception e){
System.out.println("Invalid Input!\n");
}
}
switch (choice){
case 1:
choiceNewAccount();
break;
case 2:
choiceLogin();
break;
case 3:
choiceRemoveAccount();
break;
case 4:
exit();
break;
default:
System.out.println("Invalid Input!\n");
break;
}
Case 1:
public void createAccount(){
try{
Scanner scan = new Scanner(System.in);
System.out.print("Enter Your Username: ");
String username = scan.next();
if(!isValidUsername(username)) System.out.println("Username Already Exists!");
else{
while(true){
System.out.print("Enter Your Password: ");
String pass1 = scan.next();
System.out.print("Re-Enter Your Passowrd: ");
String pass2 = scan.next();
if(!arePasswordsMatch(pass1,pass2)) System.out.println("Passowrds Don't Match!");
else {
addToAccountsList(username,pass1);
createTheUsersFile(username);
System.out.println("The Account Has Been Successfully Created!");
break;
}
}
}
} catch(Exception e){
System.out.println("Could Not Create Account!");
}
Do I need to create one System.in Object and use it on my whole program? Or is there an other way to work with the System.in Object?
So I have this code :
package Firstpack;
import java.io.*;
import java.util.*;
public class Main {
public static void menu() {
System.out.println("Welcome");
System.out.println("1. Add a record ");
System.out.println("2. See all records ");
System.out.println("3. See a category");
System.out.println("4. Total spend(Year)");
System.out.println("5. Spend in a month");
System.out.println("6. Chose by index");
System.out.println("7. Exit ");
System.out.print(">");
Scanner in = new Scanner(System.in);
int enteredInt = in.nextInt();
in.close();
switch (enteredInt) {
case 1:
recording();
break;
case 2:
System.out.print(" You have chosen -> See all records");
break;
case 3:
System.out.print(" You have chosen -> See a category");
break;
case 4:
System.out.print(" You have chosen -> Total spend(Year)");
break;
case 5:
System.out.print(" You have chosen -> Spend in a month");
break;
case 6:
System.out.print(" You have chosen -> Chose by index");
break;
case 7:
System.out.print(" Bye! ");
break;
default:
menu();
}
}
public static void recording() {
System.out.println(" You have chosen -> Add a record");
record rec = new record();
Scanner in = new Scanner(System.in);
System.out.print("Enter Amount > ");
rec.amount = in.nextDouble();
System.out.print("Enter Category > ");
rec.category = in.next();
System.out.print("Enter Details > ");
rec.details = in.next();
try {
FileWriter fw = new FileWriter("findme.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(String.valueOf(rec.amount));
bw.write(rec.category);
bw.write(rec.details);
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
}
And it throws me this:
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at Firstpack.Main.recording(Main.java:68)
at Firstpack.Main.menu(Main.java:25)
at Firstpack.Main.main(Main.java:82)
And I have no idea how to solve this. What is wrong here?
The problem is because of the call to in.close() in your menu method. Not only does in.close() close the Scanner object, but it also happens to close System.in as well. When you enter 1 as the menu selection your recording() method gets called which creates a new Scanner which tries to use the now closed System.in.
This is a post that addresses a similar issue:
Trying to write a method that checks user input in JAVA, getting NoSuchElementException
I want to make a simple menu with 3 choices:
'Create new employee', 'Display all employees' and 'Quit' in a Employee Manager(code below) but it was not successful(compiling error).
BlueJ editor cannot realize the object 'm', 's' and 'l' in the 'case 2' statement. Is there anyway to get the value of the object in the 'case 1' and use them in the 'case 2'? Thanks a lot!
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
int ch;
do{
System.out.println("EMPLOYEE MANAGER\n");
System.out.println("1. Create new employees\n");
System.out.println("2. Display all employees\n");
System.out.println("3. Quit\n");
System.out.print("Your choice: ");
Scanner input = new Scanner(System.in);
ch = input.nextInt();
switch(ch){
case 1: System.out.println("== CREATE NEW EMPLOYEES ==");
System.out.println();
Manager m = new Manager();
Scientist s = new Scientist();
Labourer l = new Labourer();
m.newManager();
s.newScientist();
l.newLabourer();
System.out.println();
break;
case 2: System.out.println("== PREVIEW EMPLOYEES ==");
System.out.println();
m.display();
s.display();
l.display();
System.out.println();
System.out.println();
break;
case 3: System.exit(0);
default: System.out.println("Invalid choice!");
}
} while(ch >= 1 && ch <=4);
}
}
They are local to block, declare them out of switch block
Manager m = new Manager();
Scientist s = new Scientist();
Labourer l = new Labourer();
switch(){...}
This answers your question well, but I would like to add few more details
if you don't put brackets with case block like
switch(i){
case 1:
String str="abc";
System.out.println(str);
case 2:
// it will give you compile time error
//duplcate local variable str
String str="abc";
}
then this str instance is visible in other case blocks as well
Q: Is there anyway to get the value of the object in the 'case 1' and use them in the 'case 2'?
A: No. The whole point of a case block is "either-or".
If you want to do "something" based on "something else", then you'll need two separate control structures.
EXAMPLE:
import java.util.Scanner;
public class Test
{
Manager m = null;
Scientist s = null;
Labourer l = null;
public static void main(String[] args) {
Test test = new Test().doIt ();
}
private void doIt () {
int ch;
do{
System.out.println("EMPLOYEE MANAGER\n");
System.out.println("1. Create new employees\n");
System.out.println("2. Display all employees\n");
System.out.println("3. Quit\n");
System.out.print("Your choice: ");
Scanner input = new Scanner(System.in);
ch = input.nextInt();
switch(ch) {
case 1:
System.out.println("== CREATE NEW EMPLOYEES ==");
getEmployees ();
break;
case 2:
System.out.println("== PREVIEW EMPLOYEES ==");
previewEmployees ();
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invalid choice!");
}
} while(ch >= 1 && ch <=4);
}
private void getEmployees () {
System.out.println();
m = new Manager();
s = new Scientist();
labourer l = new Labourer();
m.newManager();
s.newScientist();
l.newLabourer();
System.out.println();
}
private void previewEmployees () {
...
}
Define your objects m, s and l in a broader scope outside the switch. Also, initialize your objects with null value and validate them before using.
Manager m = null;
Scientist s = null;
Labourer l = null;
do{
//your code here....
switch(ch) {
case 1:
m = new Manager();
//the rest of your code here...
break;
case 2:
if (m != null) {
m.display(); //and so on
}
}
}