Passing user input between cases in switch java - java

I have a small problem with this code. I added lecturer in case 1 and I trying to add books to this lecturer in case 3. problem is that it seems that case 3 doesn't recognize the created lecturer.
Is there any way to pass this value.
The solution is probably very simple but at this hour I just can not get it...
public class Menu {
static Scanner in = new Scanner (System.in);
LectureList lec = new LectureList(100);
BookList bl = new BookList(0);
public Menu(){
}
public int mainMenu(){
int option = 0;
System.out.println("---------------------------------------------------------");
System.out.println(" Lecturer Menue ");
System.out.println("*********************************************************");
System.out.println("1) Add Lecturer");
System.out.println("2) Find Lecturer by ID");
System.out.println("3) Add book to Lecturer BookList");
System.out.println("4) Remove book from Lecturer BookList ");
System.out.println("5) Search for a book using the ISBN number");
System.out.println("6) Calculate the yearly book payment");
System.out.println("7) Output all of the book details in the system to a file");
System.out.println("8) Exit");
boolean selected = false;
while (selected == false)
{
try
{
option = in.nextInt();
in.nextLine();
if
((option == 8)){
System.out.println("Goodbye!");
System.exit(0);}
else if
((option <= 0) || (option > 8))
System.out.println("Sorry but you have to choose an option between 1 and 8");
else
selected = true;
}
catch (InputMismatchException e)
{
System.out.println("Sorry you did not enter a valid option");
in.next();
}
}
return option;
}
public void menuSwitch(){
boolean finish = false;
if (finish == false){
int option = mainMenu();
switch (option){
case 1:
String LecName = " ";
System.out.println("Please enter Lecturer's name");
LecName = in.nextLine();
Lecturer l = new Lecturer(LecName);
lec.add(l);
break;
case 2:
break;
case 3:
String name = "";
Double price = 00.00 ;
String isbn ="";
String author = "";
System.out.println("Please enter Book title ");
name = in.nextLine();
System.out.println("Please enter Book's price ");
price = in.nextDouble();
System.out.println("Please enter Book's isbn number ");
isbn = in.next();
System.out.println("Please enter book author's name");
author = in.next();
Book b = new Book( name, price, isbn, author);
l.addBook(b);
break;``
default:
finish = true;
break;
}
menuSwitch();
}
}
}

Every case statement in your switch finishes with a break;, and the default case does as well. In that case, for any pass through the switch statement, only a single case label will be executed.
If the first pass executes the first case, and the second pass executes the second case, the variables defined in the first case will no longer be around -- they will have fallen out of scope when the switch statements completes the first time.
Can you get a reference to your Lecturer from the LectureList collection?
In case 1: you can create it and put it in the collection; in case 3: you can obtain it back from the collection and update it.

Related

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;
}
}
}
}

The variable disappears at the end of the case [duplicate]

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;
}
}

Restrict Switch Statement order

I am writing a menu in java using a switch statement and while loop. I am looking to find a way of ensuring the user completes menu one before proceeding to menu two.
Here is an example piece of code:
(Please note I normally pass data using setters and getters, this is just a quick program I wrote for this question)
package menuOrder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int option = 0;
String Fname = null;
String Sname = null;
int Age = 0;
while(option !=5){
System.out.println("1. Enter Firstname");
System.out.println("2. Enter Surname");
System.out.println("3. Enter Age");
System.out.println("4. Display Details");
System.out.println("5. System Exit");
option = sc.nextInt();
switch(option){
case 1:
System.out.println("Please enter your Firstname >");
Fname = sc.next();
break;
case 2:
System.out.println("Please enter your Surname >");
Sname = sc.next();
break;
case 3:
System.out.println("Please enter your Age >");
Age = sc.nextInt();
break;
case 4:
System.out.println("Firstname = " + Fname + "\nSurname = " + Sname + "\nAge = " + Age);
break;
case 5:
System.out.println("You have chosen to System Exit!!!");
System.exit(0);
break;
default:
System.out.println("Invalid Entry!! \nPlease try again");
}
}
}
}
I am trying to prevent the use from entering their Surname before their Firstname.
Can someone please help?
Thanks
First show only the first name. Then when the user enters first name call surname method from that method.Use method calls instead of switch case.

Switch Menu Java

I have a switch menu and I want it to loop the entire menu including the directions but it just keeps looping the operation i select. How do I change it? I switched from a do/while to just a while loop.
int count = 0;
String first;
String last;
String num;
Contact person;
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
Scanner input = new Scanner(System.in);
char choice = input.next().charAt(0);
AddressBook addressBook = new AddressBook();
while ('q' != choice) {
switch (choice) {
case 'c':
System.out.println("Enter first name, last name and phone number");
addressBook.addContact();
count++;
System.out.println("Total number of contact: " + count);
break;
case 'e':
System.out.println("Enter name to be edited");
first = input.next();
last = input.next();
num = null;
person = new Contact(first, last, num);
addressBook.edit(person);
break;
case 'd':
System.out.println("Enter name to be deleted");
first = input.next();
last = input.next();
num = null;
person = new Contact(first, last, num);
addressBook.removeContact(person);
break;
default:
System.out.println("Operation does not exist");
}
}
}
}
Initialize char choice to a default char:
char choice = 'a';
Then move all of this:
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
choice = input.next().charAt(0);
Inside your while loop:
while ('q' != choice) {
//show menu options
//allow user to select a menu option
//use switch to operate based on user decision
//once the operation is complete, as long as the user didn't select q,
//the menu options show once more and allow another selection
}
No need to use choice.
1.Change while ('q' != choice) to while (true)
2.Move below code inside while
System.out.println("What would you like to do?");
System.out.println("Type c to create");
System.out.println("Tpe e to edit");
System.out.println("Tpe d to delete");
System.out.println("Type q to quit");
3. Add one extra case
case 'q':
break;

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