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
Related
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'm currently testing running 2 or more switches, however I'm having issues with how they prioritise themselves. For example -
switch (Scanner Input)
{
case 1:
System.out.print("Example");
break;
case 2:
get.example();
break;
}
switch (Scanner Input2)
{
case 1:
System.out.print("Example");
break;
case 2:
get.example();
break;
}
If I was to run this, it would ask for both of my inputs and THEN does prints out/runs method. Instead of switch 1 > runs outcome > switch 2 > runs outcome. Also if there is a fix, is it possible to do it in a loop?
Hopefully this makes some kind of sense, I'm still new so my terminology is off. Thanks massively in advance!
you can do it by moving your switch logic to another method and then invoke it if it is meant to do the same, so you don't write it twice, here a piece of code that can help you and that's how I think you want to do this, I added some messages to the user there.
I removed the breaks in the cases because I'm using return, so it would be unreachable code.
import java.util.Scanner;
public class Pregunta {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Press 0 to exit.");
int input = scanner.nextInt();
while ( input != 0 )
{
System.out.println( switchUsersInput(input));
System.out.println("Press 0 to exit.");
input = scanner.nextInt();
}
System.out.println("Finish.");
}
public static String switchUsersInput( int input )
{
switch (input)
{
case 1:
return "Example";
case 2:
return "Example 2 I didn't get your get.example();";
default:
return "Chose something :)";
}
}
}
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'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.
}
I'm kinda new to this but? can anyone correct my first switch statement? I dont know what expression to use to start the case a:
and im not even sure if the starting declarations are even correct
import java.io.*;
public class SwitchDemo {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input= br.readLine();
System.out.println("Press Enter");
System.out.println("a.Hello: Asks the name of the user.");
System.out.println("b.Array: Input elements and search for a specified key and prints a message.");
System.out.println("c.MagicSquare: Displays [7][7] magic square.");
System.out.println("d.Bubble Sort: Alphabetically sorts 20 employees using bubble sort.");
System.out.println("e.Selection Sort: Alphabetically sorts 20 employees using selection sort");
System.out.println("f.Insertion Sort: Alphabetically sorts 20 employees using Insertion sort");
System.out.println("g.Factorial: Run the Factorial application");
System.out.println("h.Triangle: Run the Triangle application.");
System.out.println("i.MergeSort: Performs the mergesort of a two class databasse.");
System.out.println("j.Stack_1: Perform reversal of string.");
System.out.println("k.Stack_2: Perform Infix Notation");
System.out.println("l.Postfix: Perform Postfix Notation");
System.out.println("m.Linked List");
System.out.println("n.Queue:");
System.out.println("o.Exit:");
switch (input) {
case a:
String usersName;
String upperCaseName;
TextIO.put("Please enter your name: ");
usersName = TextIO.getln();
upperCaseName = usersName.toUpperCase();
TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
break;
case b:
// Code for b execution here. Run array.
break;
case c:
// Code for c execution here. magicsquare.
break;
case d:
// Code for d execution here. Bubble sort.
break;
case e:
// Code for e execution here. selection sort.
break;
case f:
// Code for f execution here. insertion sort.
break;
case g:
// Code for g execution here. recursion.
break;
case h:
// Code for h execution here. mergesort.
break;
case i:
// Code for b execution here. stack1.
break;
case j:
// Code for b execution here. stack2.
break;
case k:
// Code for b execution here. link list.
break;
default:
System.out.println("Please input selection from a-o");
break;
}
}
}
As others have mentioned, using
switch(input) {
case "a":
// do stuff
break;
case "b":
// do more stuff
break;
}
will work.
Just another thing, if you are working in java 7 (java -version), you should be able to get rid of
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
and replace it with
Scanner in = new Scanner(System.in);
String input = in.nextLine();
Which at least to me is a lot easier to use. Just import
import java.util.Scanner;
A couple of points here
case statements are like this (pre 1.7)
char input = 'a';
switch (input) {
case 'a':
break;
default :
System.out.println("default");
}
for Java 1.7 and onwards you can also switch on Strings
String input = "a";
switch (input) {
case "a":
printHelloUser();
break;
default :
System.out.println("default");
}
void printHelloUser () {
String usersName;
String upperCaseName;
TextIO.put("Please enter your name: ");
usersName = TextIO.getln();
upperCaseName = usersName.toUpperCase();
TextIO.putln("Hello, " + upperCaseName + ", nice to meet you!");
}
you may also want to consider prompting the user first before reading her input.
You aren't checking the cases as Strings (you declare input as a String). You are calling variables called a, b, etc. Try putting them into quotation marks, as in case: "a".