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.
Related
This program is a contact book. There is a contact class and contact book class. When I execute case 2, the add method from the contact book class does not let me enter name and phone number individually. "Enter a name" and "Enter an address" appear at the same time.
Here is the switch case in the main method:
while (!done)
{
ContactBook cb = new ContactBook();
System.out.println("1) List all contacts" + "\n" + "2) Add a contact"
+ "\n" + "3) Update a contact" + "\n" + "4) Remove a contact" +
"\n" + "5) Quit");
userChoice = sc.nextInt();
switch (userChoice)
{
case 1:
c.toString();
break;
case 2:
cb.add(sc);
break;
case 3:
cb.update(sc);
break;
case 4:
cb.remove(sc);
}
if (userChoice == 5);
{
done = true;
}
}
}
Here is the add method from the contact book class:
public void add (Scanner sc)
{
Contact c = new Contact(name, address, phone, email);
System.out.println("Enter a name: ");
c.setName(sc.nextLine());
System.out.println("Enter an address: ");
c.setAddress(sc.nextLine());
System.out.println("Enter a phone number: ");
c.setPhone(sc.nextLine());
System.out.println("Enter an email: ");
c.setEmail(sc.nextLine());
entries = Arrays.copyOf(entries, entries.length + 1);
}
You need to change the following:
userChoice = sc.nextInt();
to
userChoice = Integer.valueOf(sc.nextLine());
I think this should fix your problem
System.out.print("Enter a name: ");
c.setName(sc.nextLine());
System.out.println()
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;
}
}
}
}
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 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.
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.