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;
Related
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.
My program is stuck in an infinite loop after a selection is made and completed. It needs to restart and go through the menu options again. Any help would be greatly appreciated.
public static void main(String[] args) {
// TODO Auto-generated method stub
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
int choice = input.nextInt();
int count = 0;
while (choice < 1 || choice > 6){
count ++;
System.out.println("I'm sorry, " +choice+ " is not a valid option.\n");
System.out.println("Menu");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Generate a random number");
System.out.println("6. Quit\n");
System.out.print("What would you like to do? ");
choice = input.nextInt();
if (choice >= 1 && choice <= 6){
continue;
}
else if (count == 2){
System.out.println("Please try again later.");
System.exit(0);
return;
}
}
do
{
switch (choice)
{
case 1: choice = 1;
System.out.print("What is the first number? ");
int firstAdd = input.nextInt();
System.out.print("What is the second number? ");
int secondAdd = input.nextInt();
System.out.println("Answer: " +(firstAdd + secondAdd));
break;
case 2: choice = 2;
System.out.print("What is the first number? ");
int firstSub = input.nextInt();
System.out.print("What is the second nubmer? ");
int secondSub = input.nextInt();
System.out.println("Answer: " +(firstSub - secondSub));
break;
case 3: choice = 3;
System.out.print("What is the first number?" );
int firstMult = input.nextInt();
System.out.print("What is the second number? ");
int secondMult = input.nextInt();
System.out.println("Answer: " +(firstMult * secondMult));
break;
case 4: choice = 4;
System.out.print("What is the first number? ");
double firstDiv = input.nextInt();
System.out.print("What is the second number? ");
double secondDiv = input.nextInt();
while (secondDiv == 0){
System.out.println("I'm sorry, you can't divide by zero.");
break;}
{
System.out.println("Answer: " +(firstDiv / secondDiv));
break;
}
case 5: choice = 5;
System.out.println(Math.random() * 10 + 1);
break;
case 6: choice = 6;
System.out.println("Goodbye!");
System.exit(0);
return;
}
}while (choice >=1 && choice <= 6);
}
I've tried a few different options that I found in my book, but they seem to cause more errors in other areas. I don't know if there is a different statement than "break;" to use to restart the menu because this is my first time using cases.
Enclose everything after the scanner instantiation in a while loop.
Specifically,
while (true) {
// your code
if (choice == 6)
break;
}
FIXED: Also remove the do {} while() loop. Your loop is infinite because "choice" does not change in the loop.
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.
The code will compile, but there seems to be an error with my menu. The user will select one of the choices and the program should execute, but When choosing a selection nothing happens. Here is the code:
import java.util.Scanner;
class Tutorial{
public static void main(String args[]){
Geek myGeek = new Geek("Geek");
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
Scanner scan = new Scanner(System.in);
String choice = scan.nextLine();
do {
switch (choice){
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
int input2 = scan.nextInt();
System.out.println("Enter the third number");
int input3 = scan.nextInt();
myGeek.allTheSame(input1, input2, input3);
break;
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
myGeek.sum(num1, num2);
break;
case "e":
System.out.println("Enter a string: ");
String word1 = scan.nextLine();
System.out.println("Enter an integer: ");
int numberOfTimes = scan.nextInt();
System.out.println("Enter the third number");
myGeek.repeat(word1, numberOfTimes);
break;
case "f":
System.out.println("Enter a string: ");
String word2 = scan.nextLine();
myGeek.isPalindrome(word2);
break;
case "?":
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
break;
} }while (choice != "q");
}
}
Here is the what it looks like when run:
http://i.imgur.com/O6SgyH1.png
Well, you definitely need to move code which gets input inside the loop :
String choice = null;
Scanner scan = new Scanner(System.in);
do {
choice = scan.nextLine();
switch (choice) {
case "a":
.........
} // end of switch
} while (!choice.equals("q")); // end of loop
Otherwise, you input once and switch on that input indefinitely (unless it is "q")
Edit :
You also need to change terminating condition to while (!choice.equals("q"));
for it to work.
This also depends on which version of the JDK they're using.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
http://java.dzone.com/articles/new-java-7-feature-string
Few things:
You read input only once - outside of do..while - probably not what you want (otherwise you'd be stuck in infinite loop).
most likely the intent was this: while ((choice = scan.nextLine()) != "q");
As far as why you don't see anything when running, it depends on what myGeek.getName() does.
As name suggests its a simple getter, if this is a case then it returns the name but it does not print anything on the screen.
i think you want something like this:
....
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
String choice;
do {
System.out.println("Select something: ");
Scanner scan = new Scanner(System.in);
choice = scan.nextLine();
switch (choice){
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
....
if not --->>>> for what you need do -> while??
and check, if your java is 7 or heighter, and check your getMethods() -> if thay return anything
One issue you have, as mentioned by #rgettman, is that comparing Strings in Java using == or != will compare the Object reference of the String not the value; basically are the two Strings the same Object? In this case (and most cases) you want to compare the value.
Change while (choice != "q"); to while (!choice.equals("q")); to compare the values.
A slightly different explanation:
Right now you are entering a character, say "a", matching your case for "a" and breaking from the switch/case. However when your program gets to the while it basically checks whether choice is "q" so your program goes back into the do/while loop.
Your loop (do {} while(condition)) will loop infinite when you enter some string different "q" because condition always is true.
try with :
while (!choice.equals("q")) {
switch (choice) {
case "a":
myGeek.getName();
break;
case "b":
myGeek.getnumberofQuestions();
break;
case "c":
System.out.println("Enter the first number");
int input1 = scan.nextInt();
System.out.println("Enter the second number");
int input2 = scan.nextInt();
System.out.println("Enter the third number");
int input3 = scan.nextInt();
myGeek.allTheSame(input1, input2, input3);
break;
case "d":
System.out.println("Enter the first number");
int num1 = scan.nextInt();
System.out.println("Enter the second number");
int num2 = scan.nextInt();
myGeek.sum(num1, num2);
break;
case "e":
System.out.println("Enter a string: ");
String word1 = scan.nextLine();
System.out.println("Enter an integer: ");
int numberOfTimes = scan.nextInt();
System.out.println("Enter the third number");
myGeek.repeat(word1, numberOfTimes);
break;
case "f":
System.out.println("Enter a string: ");
String word2 = scan.nextLine();
myGeek.isPalindrome(word2);
break;
case "?":
System.out.println("Command Options: ");
System.out.println("a: Geek's Name");
System.out.println("b: Num Questions Asked");
System.out.println("c: All Numbers Are the Same");
System.out.println("d: Sum Between Two Integers");
System.out.println("e: Repeat the String");
System.out.println("f: It is Palindrome");
System.out.println("?: Display");
System.out.println("q: Quit");
break;
}
}
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.