I'm currently hardcoding an enum value, which is running through a switch statement. Is it possible to determine the enum based on user input.
Choice month = Choice.D;
Instead of hardcoding the value D, can I use the user input here?
package partyAffil;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class partyAffil {
public static void main(String[] args) {
System.out.println("Choose from the following menu");
System.out.println("D, R, or I");
String choice = getInput("please choose a letter.");
Choice month = Choice.D;
switch(month){
case D:
System.out.println("You get a Democratic Donkey");
break;
case R:
System.out.println("You get a Republican Elephant");
break;
case I:
System.out.println("You get an Independent Person");
break;
default:
System.out.println("You get a unicorn");
break;
}
}
public enum Choice{
D, R, I;
}
private static String getInput(String prompt)
{
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
System.out.print(prompt);
System.out.flush();
try{
return stdin.readLine();
} catch (Exception e){
return "Error: " + e.getMessage();
}
}
}
Each enum constant have its own name as declared in its declaration. Static method valueOf of particular enum returns the enum constant of this type by name.
Thus, instead:
Choice month = Choice.D;
just use this:
Choice month = Choice.valueOf(choice);
What if you create the switch on the input rather than the month (or both, if they must be implemented separately)?:
Choice month;
switch(choice.toUpperCase()){
case 'D':
month = Choice.D
System.out.println("You get a Democratic Donkey");
break;
...
}
Better yet, I believe you could even set the character values in the enum:
public enum Choice{
D('D'), R('R'), I('I');
}
This way, instead of case 'D': you can still use case D:
(Not sure about that one, I am more used to C-based languages)
Above given answers might help.
If you are not an expert, use following code that will you understand the steps.
public void run() throws Exception
{
switch (menu() ) //calling a menu method to get user input.
{
case 1:
//fyi, make sure you have all the methods in your code that is given for each menu choice.
//you can have print statement in your method.
// e.g. System.out.println("You get a Democratic Donkey");
method1();
break;
case 2:
method2();
break;
case 3:
method3();
break;
case 0:
return;
//following default clause executes in case invalid input is received.
default:
System.out.println ( "Unrecognized option" );
break;
}
}
private int menu()
{
//list of menu items.
System.out.println ("1. insert appropriate description for your menu choice 1.");
System.out.println ("2. ");
System.out.println ("3. ");
System.out.println ("4. ");
return IO_Support.getInteger(">> Select Option: ", "Unrecognized option"); //you can use scanner to get user input. I have user separate class IO_Support that has getInteger methods to validate int user input. the text "unrecognized option" is what the message that i want to print if the option is integer but not valid choice.
}
Related
I am trying to make a program where the user has to answer a multiple choice question. The program works completely fine when the user enters A, B, C, or D. But if they enter "Z" for example, it stops working at a certain point. The program will proceed as prompted by saying "Invalid answer, please enter A, B, C, or D." But when you select A, B, C, or D, the program suddenly ends instead of showing whether or not the user was correct.
I tried to call the getAnswer() method again as the default case in the switch statement, so the program will ask the user for their choice again. Before I added this line, it didn't do that at all. However, it's still not following through with that last step. Here's the code:
// Call the method that will ask the user the question.
askQuestion();
// Call the method that will allow the user to answer.
getAnswer();
switch(userChoice)
{
case 'a':
case 'A':
System.out.println("Incorrect! 'Switch' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
case 'b':
case 'B':
System.out.println("Correct!");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
case 'c':
case 'C':
System.out.println("Incorrect! 'Float' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
case 'd':
case 'D':
System.out.println("Incorrect! 'True' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
break;
default:
System.out.println("Invalid character.");
// Repeats the getAnswer method to retrieve a valid character.
getAnswer();
}
}
// method that will ask the question
public static void askQuestion()
{
// Show the user the possible answers for the multiple choice questions.
System.out.println("Which of these is NOT a Java key word?");
System.out.println("A: switch");
System.out.println("B: keyboard");
System.out.println("C: float");
System.out.println("D: true");
}
// method that will retrieve the answer from the user
public static char getAnswer()
{
// create another Scanner object
Scanner keyboard = new Scanner(System.in);
// Tell the user to select their answer and store it in a variable.
System.out.println("Select your answer by pressing A, B, C, or D.");
String input = keyboard.nextLine();
userChoice = input.charAt(0);
// Return the user's answer to main.
return userChoice;
}
Ideally, if the user presses Z, but then presses A the next time around, it will tell the user is wrong, but the program is just ending instead of providing feedback. What am I missing?
It's best to use a loop here. You keep looping until the user enters a valid response:
askQuestion();
while (true) {
userChoice = getAnswer();
switch(userChoice)
{
case 'a':
case 'A':
System.out.println("Incorrect! 'Switch' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
...
default:
System.out.println("Invalid character.");
}
}
Note that you don't need the break statements after each System.exit(0) call.
You could move the askQuestion() call inside the while loop if you wanted to re-ask the question on a bad input.
you can use a recurring method call when an invalid answer is received
public void doProcess(){ //this will keep getting called until a valid key is read.
askQuestion();
userChoice = getAnswer();
switch(userChoice)
{
case 'a':
case 'A':
case 'b':
//program will exit/ correct wrong ans etc etc
break;
default:
//call itself again
doProcess();
}
}
Your switch case only checks for a single time only for the first answer.
You can have function for finidng the answer itself.
import java.util.Scanner;
public class Main
{
// method that will ask the question
public static void askQuestion()
{
// Show the user the possible answers for the multiple choice questions.
System.out.println("Which of these is NOT a Java key word?");
System.out.println("A: switch");
System.out.println("B: keyboard");
System.out.println("C: float");
System.out.println("D: true");
}
// method that will retrieve the answer from the user
public static char getAnswer()
{
// create another Scanner object
Scanner keyboard = new Scanner(System.in);
// Tell the user to select their answer and store it in a variable.
System.out.println("Select your answer by pressing A, B, C, or D.");
String input = keyboard.nextLine();
char userChoice = input.charAt(0);
// Return the user's answer to main.
return userChoice;
}
public static void main(String[] args) {// Call the method that will ask the user the question.
askQuestion();
// Call the method that will allow the user to answer.
char userChoice = getAnswer();
while(!checkForCorrectAnswer(userChoice)){
userChoice = getAnswer();
}
}
private static boolean checkForCorrectAnswer(char userChoice){
switch(userChoice)
{
case 'a':
case 'A':
System.out.println("Incorrect! 'Switch' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
case 'b':
case 'B':
System.out.println("Correct!");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
case 'c':
case 'C':
System.out.println("Incorrect! 'Float' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
case 'd':
case 'D':
System.out.println("Incorrect! 'True' IS a key word. The correct answer was B. ");
System.out.println("The program will now end. Thanks for answering!");
System.exit(0);
return true;
default:
System.out.println("Invalid character.");
// Repeats the getAnswer method to retrieve a valid character.
return false;
}
}
}
To avoid having to use the case expression to verify if it is lowercase or uppercase, I recommend that you use the following:
String value = String.valueOf(userChoice).toUpperCase();
This helps to make the conversion of lowercase to uppercase before doing the evaluation in the switch case.
first question:
There is a do while loop, within the do section there is a switch. After selection case 1, some calculations are done, two options can result as shown in the If statement. My problem is code runs until the break; then just goes straight back to the menu loop. My question: how do i get the program to print the output for the user, then continue the menu loop?
Second question:
In case 1 there are two resulting options, the first being a failed response. from here, how do i get the program to loop back to the start of case 1 to ask for user input again? Even back to the main menu would be fine.
public static void showMenu() {
System.out.print('\u000c');
System.out.println("1 - Compute Change \n");
System.out.println("2 - Estimate Feast \n");
System.out.println("3 - \n");
System.out.println("4 - \n");
System.out.println("5 - I'm broke, get me out of here\n");
System.out.println("Select Option:\n");
}
public StackPost() {
System.out.println("Welcome to the Bank of Winterfell");
Scanner in = new Scanner(System.in);
do {
showMenu();
selection = in.nextInt();
switch (selection) {
case 1:
// get input, compute then decision:
if (something<somethingElse) {
// false response -
} else {
// correct response - system prints out some stuff back to user, back to main
// menu loop
}
break;
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
break;
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
You could print "Press enter to continue" (or whatever you want to give notice of before locking the program), and add a call to Scanner#nextLine() before your break. This will lock the progression 'till user presses enter.
case 2:
// Some code here...
// Done, now show result and tell user to press any key to continue
System.out.println("Some fancy result from case handle code");
System.out.println("Press enter to continue...");
in.nextLine();
break;
You could add a while-loop that won't let the code continue 'till whatever input is expected in the first case is acceptable.
case 1:
System.out.println("Some handle that tells user to input something, and what is acceptable");
String input = null;
while(!(input = in.nextLine()).equals("something")) {
System.out.println("Wrong input, try again...");
}
// Input is acceptable, now do something with it...
System.out.println(input);
System.out.println("Press enter to continue...");
in.nextLine();
break;
Be aware, in your code, you call Scanner#nextInt(), and #nextInt doesn't consume the \n from pressing enter, and will thus be transferred into the switch case's usage of #nextLine(). You could avoid this with selection = Integer.parseInt(in.nextLine()).
You can use achieve it by:
For First question: Using return statement in case of correct response.
For Second question: Using while loop in case 1
After implementaing the proposed solution the StackPost() method will look like following. You can see the complete working code here:
public static void StackPost()
{
System.out.println("Welcome to the Bank of Winterfell");
try(Scanner in = new Scanner(System.in))
{
int selection;
do
{
showMenu();
selection = in.nextInt();
switch (selection)
{
case 1:
// get input, compute then decision:
while(true)
{
int something = in.nextInt();
int somethingElse = in.nextInt();
if (!(something<somethingElse)) {
// correct response - system prints out some stuff back to user, back to main
System.out.println("Print here the result");
// menu loop
return;
}
// false response - continue for next iteration in while-loop
}
//No need of 'break;' here
case 2:
break;
case 5:
System.out.println("\nEnding Now\n");
System.exit(0);
default:
System.out.println("Instruction is invalid");
}
} while (selection != 5);
}
}
Note: It is best practice to use try-with-resources while handling system resources which implements AutoCloseable interface.
I have an assignment at school to create a program with at least three separate methods that will act like a 'Magic Eight Ball". I have already created the method with 10 'responses' set to a 'switch' statement, based on a separate method that generates a random number between 0 and 9. What I need is a 'for', 'while', or 'do while' loop method that is supposed to continue asking questions until the word 'exit' is entered as a question. then I need a way to tie all of these methods together so they work right. I use a program called BlueJ (as instructed by the prof)
What I have so far is:
import java.util.*;
public class MagicEightBall
{
//Input method
public static void main(String[] args)
{
startAsking();
}
//Loop method
public static void startAsking()
{
do
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Question: ");
System.out.println("Entering 'exit' ends program ");
if(input.nextLine().equalsIgnoreCase("exit"))
break;
System.out.println(getResponse());
}
while(true);
//input.close();
}
//Output method
public static String getResponse()
{
int numberOfResponses = 10;
int response = (int)(Math.random() * numberOfResponses);
String responseString;
switch (response)
{
case 1: System.out.println("Of course! H-A-L said so");
case 2: System.out.println("Yes, my young Padawan!");
case 3: System.out.println("V-ger has informed me that your answer is 'Yes'");
case 4: System.out.println("Mr. Spock says 'Not a chance, Captain'");
case 5: System.out.println("Only when Pi = apple would that be a 'Yes'");
case 6: System.out.println("There is no try, only do, or do not");
case 7: System.out.println("You know 'Big Brother' heard you ask that question?");
case 8: System.out.println("SyStEm MaLfUnCtIoN! pLeAsE tRy l8r");
case 9: System.out.println("No. That would cause a food fight");
default: System.out.println("I'm sorry, it's time for my oil bath");
}
return responseString;
}
}
Any help as to how to complete this would be greatly appreciated.
I build your code , then run it ;
reading about what are u asking its seems do everything (but not 100% correct) , in this steps:
1 ask u a question
2 answer u random
3 if asked "exit" he stop the program
can u explain me better what miss in your program that you need ? not doing at the moment?
for now i just can say you use a variable for append the question , than use the variable for go put from the loop also there is something not needed in the getresponse method
import java.util.*;
public class NewClass
{
//Input method
public static void main(String[] args)
{
startAsking();
}
//Loop method
public static void startAsking()
{
do
{
Scanner input = new Scanner(System.in);
System.out.print("Enter Question: ");
System.out.println("Entering 'exit' ends program ");
if(input.nextLine().equalsIgnoreCase("exit"))
break;
getResponse();
}
while(true);
//input.close();
}
//Output method
public static void getResponse()
{
int numberOfResponses = 10;
int response = (int)(Math.random() * numberOfResponses);
System.out.println(response);
switch (response)
{
case 1: System.out.println("Of course! H-A-L said so");break;
case 2: System.out.println("Yes, my young Padawan!");break;
case 3: System.out.println("V-ger has informed me that your answer is 'Yes'");break;
case 4: System.out.println("Mr. Spock says 'Not a chance, Captain'");break;
case 5: System.out.println("Only when Pi = apple would that be a 'Yes'");break;
case 6: System.out.println("There is no try, only do, or do not");break;
case 7: System.out.println("You know 'Big Brother' heard you ask that question?");break;
case 8: System.out.println("SyStEm MaLfUnCtIoN! pLeAsE tRy l8r");break;
case 9: System.out.println("No. That would cause a food fight");break;
default: System.out.println("I'm sorry, it's time for my oil bath");
}
}
}
dont care about some output i add for control the loop
I have an assignment for my Java class to program a Magic 8-ball. It is supposed to generate a random number for the response, contain a "while(true)" statement, and a switch statement for the replies. This is what I have so far. I can't seem to figure out how to work the "while(true)" statement in without it repeating infinitely.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String question;
int retry;
int q1;
System.out.print("What is your question for the Magic 8-bit 8-ball? ");
question = input.next();
System.out.print(process());
/*This is where I am having the problem. How do I work a "while(true)" in
* to where this won't infinitely repeat?
*/
}
public static int process() {
Random rand1 = new Random();
int random = rand1.nextInt(9);
int ans = random;
switch (ans) {
default: System.out.println("Does not compute!! Error! Error!");break;
case 1: System.out.println("The answer is.............. 42");break;
case 2: System.out.println("To get to the other side!!!");break;
case 3: System.out.println("Out of memory! Try again!");break;
case 4: System.out.println("Who do you think I am, IBM's Watson?");break;
case 5: System.out.println("Danger Will Robinson!! Danger!!");break;
case 6: System.out.println("What do you think?");break;
case 7: System.out.println("Fatal error.....nahhh just kidding");break;
case 8: System.out.println("Well, this is fun....NOT!");break;
case 9: System.out.println("Um...... 1,000,000,000,000,000,000,000?");break;
}
return ans;
}
}
Hum, the point of a while (true) loop is to be infinite, unless you add a break statement in it.
while (true) {
doStuff();
// if someCondition is true, this will exit the loop
if (someCondition)
break;
}
Note that this is equivalent to
do {
doStuff();
} while (!someCondition);
or
boolean someCondition = false;
while (!someCondition) {
doStuff();
}
It is usually preferrable to not have an infinite loop (while (true) for example) and have an explicit condition instead. Some exceptions exist, for example if the condition is complicated to express or if you want to break the loop at a particular position of the loop and not at the beginning or at the end :
while (true) {
doStuff();
if (someCondition)
break;
doSomeOtherStuff();
}
One of the many possible ways:
Create a a char and assign it to 'Y' (i.e. char continueLoop = 'Y').
Use this to control the while statement (i.e. while(char == 'Y') ).
Ask the user for input and process the input (i.e. System.out.println("Continue? Y/N") and then use Scanner to read the input and assign it to continueLoop.
You can create something similar using booleans.
I am having trouble getting my menu below to run from my driver. The program will execute, however it will not display my menu until I enter a number. After that it will display properly, and it reads selection properly, but will not call the methods I have listed in the case statement.
For instance, if I input a '1', the menu will recognize I input a 1 and will display the menu again with "You entered 1". instead of calling dec.getDec(), as it should according to the case statement. Any helpful hints or advice would be appreciated. This is a homework assignment, and I am not trying to get someone to write the code for me or anything. I just need to be pointed in the right direction please.
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class Menu {
Scanner scan = new Scanner(System.in);
int selection;
public int GetSelection()
{
selection = scan.nextInt();
return selection;
}
public void display()
{
System.out.println("Please choose an option from the following:");
System.out.println("[1] Convert Decimal to Binary");
System.out.println("[2] Convert Decimal to Hexadecimal");
System.out.println("[3] Convert Binary to Decimal");
System.out.println("[4] Convert Binary to Hexadecimal");
System.out.println("[5] Convert Hexadecimal to Decimal");
System.out.println("[6] Convert Hexadecimal to Binary");
System.out.println("[0] Exit");
System.out.println("\n");
System.out.println("You entered: " + selection);
}
}
----------------------------
import java.io.*;
import java.lang.*;
import java.util.Scanner;
public class Driver
{
public static void main(String[] args)throws IOException {
LineWriter lw = new LineWriter("csis.txt");
int selection;
Decimal dec = new Decimal();
Binary bin = new Binary();
Hexadecimal hex = new Hexadecimal();
Menu menu = new Menu();
do{
menu.display();
selection=menu.GetSelection();
switch (selection){
case '1':{ dec.getDec();
break;}
case '2':{ dec.getHex();
break;}
case '3':{ bin.getBin();
break;}
case '4':{ bin.getHex();
break;}
case '5':{ hex.getHex();
break;}
case '6': { hex.getDec();
break; }
//default: System.out.println("Error: Unrecognized Selection");
// break;
}
}while (selection !=0);
}
}
As this is homework, I won't give you the whole solution, but I'll help get you there...
Your problem is coming from your use of Scanner, the helpful part of this page is A scanning operation may block waiting for input.
Using that you should be able to see where the problem is, if you need more help comment on this answer and I'll see if there's more I can do.
Don't use case 'n':, just use case n. You don't need the single quote. Also have a look at this tutorial on Switch Statements in Java to get an idea of how to use this in your code.
The problem with your current implementation is because you're trying to compare an int value (that you've in your selection variable) with char (which is internally getting converted to its corresponding int value i.e. int value of '1' is not the same as 1).
You can see the difference with the following code:
switch(selection){
case '1':
System.out.println("Hello World from char");
break;
case 1:
System.out.println("Hello World from int");
break;
}
So when you set selection = 1, you would find the output from the int block however if you set selection = '1', you would find the output from the char block
Note that I'm assuming that you're not running in Java 7
Note: There's another issue with your code. #Shaded has given you the perfect hint. Think about it with reference to how your control flows through your logic for setting the value of selection variable.