Why isn't my output showing after my switch statement - java

I'm learning Java right now and I've never used switch statements before. I tried to enter a simple charmed quiz, but something in the switch statement isn't working.
I've tried putting text at various points in the program to test if the program every reaches that code. I have a good response inside the actual switch, so If I answer Question 1 wrong the text prompt will show up. But any later than inside the switch statement and none of my scoring output appears until all iterations of the for loop are complete. I have tried moving the "correct/incorrect" output to various points and none of them seem to work.
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter your name!");
String name = myScanner.nextLine();
int wrongCounter = 0;
boolean correctChecker = false;
int score = 0;
String answer;
System.out.println("Welcome to the Charmed Quiz, " + name + "!");
for (int i = 0; i < 10; i++) {
if (wrongCounter < 4) {
switch(i) {
case 0:
System.out.println("Who read the spell that gave the Charmed Ones their powers?");
System.out.println("Enter your answer");
answer = myScanner.nextLine();
switch (answer) {
case "Pheobe":
correctChecker = true;
break;
default:
correctChecker = false;
break;
}
case 1:
System.out
.println("Who travelled to a cursed town with Prue when Pheobe was shot in a premonition?");
System.out.println("Enter your answer");
answer = myScanner.nextLine();
switch (answer) {
case "Cole":
correctChecker = true;
break;
default:
correctChecker = false;
break;
}
}
if (correctChecker == true) {
score++;
System.out.println("Correct!");
} else {
wrongCounter++;
System.out.println("Incorrect!");
}

This definitely isn't the best way of achieving a quiz game, but if you're using this as a learning exercise then the best course of action is to take the advice from #rzwitserloot.
Add a break after your main switch statement cases as opposed to the inner switch statement.
There is no real use having an inner switch statement though when you can use correctChecker = "Pheobe".equals(answer); to get a true or false boolean value in a single line.
This just means you can avoid the second switch statement which makes it way less confusing.
Altogether your cases could look something like this:
case 0:
System.out.println("Who read the spell that gave the Charmed Ones their powers?");
System.out.println("Enter your answer");
answer = myScanner.nextLine();
correctChecker = "Pheobe".equals(answer);
break;
}
In future, it would be better to store questions and answers in an array and use the for loop to iterate through that. This is a good tutorial on the subject.
Good luck with the rest of your project!

There are many, many problems with this code. The primary issue is that break breaks the closest construct it can break, which in your case is the inner switch. Whereas your intent is clearly to break out of both. Either [A] add another break right before the case 1: statement, or [B] use a labelled break; put something like outer: before the first (primary/outer) switch, and then make all those statements break outer;.
But, really, none of this (either the outer or the inner) are in any way sensible in switch form. I get that this is a learning exercise, but I'd think of something else to learn with.
Also, it's Phoebe, not Pheobe.

Related

How do I keep looping in a do-while loop as long as the default part of a switch triggers?

What I am trying to accomplish: when the user types in anything other than 1 or 2, there will be a prompt saying "I don't understand you" and it would ask the user to choose 1 or 2 again without having to run the program each time.
Something like this:
do {
String a = input.nextLine();
num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
break;
case 2:
System.out.println("goodbye");
break;
default:
System.out.println("I don't understand you");
}
} while (num == default);
I know typing this will give me an error, so how do I compare it?
First, you have a potential infinite loop because the value for num which controls the stoping condition is never updated inside the loop.
Second, you could introduce a local variable to track when the user input was understood and exit the loop on that condition:
boolean understood;
do {
understood = false;
String a = input.nextLine();
int num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
understood = true;
break;
case 2:
System.out.println("goodbye");
understood = true;
break;
default:
System.out.println("i dont understand u");
break;
}
} while (!understood);
What you asked is technically a while(true) since everything which is not 1 or 2 is default. Also you should probably put your scanning bit in the loop.
If you try to check if value is different from 1 and 2 to ask again for a valid option:
do
{
// stuff
}
while( num != 1 && num != 2)
Since "default" is a keyword you just can not compare it to anything. It's meaningless though, because in your condition you used all possible cases(case 1 and case 2), so your code will never end, printing either "hello" or "goodbye" forever.

I don't know how to leave this looping structure

Ok, so the code below loops wonderfully. It can loop as long as it wants to. The thing is though, I can never get out of the loop. I'm trying to build a text-adventure, by the way for those wondering, but I really need to get out of this loop.
System.out.println("\n\nWelcome, " + name + "! To proceed, enter your class of fighter.");
System.out.println();
boolean x = true;
while (x){
//information print statements
System.out.println("What will your class be? ");
String heroclass = scan.nextLine();
heroclass.toLowerCase();
String A;
switch (heroclass)
{
case "slayer": A = "You have selected the Slayer class.";
break;
case "blader": A = "You have selected the Blader class.";
break;
case "bandit": A = "You have selected the Bandit class.";
break;
case "wizard": A = "You have selected the Wizard class.";
break;
default: A = "Invalid entry.";
break;
}
String killloop = A;
if (killloop.charAt(0) == 'Y'){
x = false;
}
}
You need to assign heroclass.toLowerCase(); to the original value of heroclass:
heroclass = heroclass.toLowerCase();
If you do not do this, the lowercase version of heroclass is not saved.
heroclass is of String type. String is immutable type of object, so you can't update this string. heroclass.toLowerCase() just return another String object with lower cased characters, so you need to reassign this string result to this variable:
heroclass = heroclass.toLowerCase();
Put your loop in a labeled block:
myblock: {
while (true) {
//code
heroclass = heroclass.toLowerCase();
switch(heroclass)
{
case "slayer": A = "text";
break myblock;
//repeat with other cases
}
}
}
//goes to here when you say "break myblock;"
What you're doing is basically assigning the label myblock to the entire loop. When you say break myblock it breaks out of the entire section inside of the brackets.
NOTE: I would recommend this solution over the others because it doesn't depend on the magic value assigned by the switch; it works no matter what it is.
Also, I've added the part to make it case insensitive. Sorry about the confusion!
Although coding wombat is right, i'm not a big fan of the way you did things here. A loop around your whole program like this isn't good practice. It's super clunky and will lead to many problems, not to mention you're making things more complicated for yourself. Ideally you'd want to put this class selection part of the program inside a method. Then if the user's input is invalid, simply call back the method recursively until you get correct input.
Ex.
case A: do this...
case B: do this...
case C: System.out.println("Not a valid input);, classSelector();
Also, when you use OOP you have the benefit of storing all the player's attributes inside an object, as well as making methods that manipulates those attributes. It will make your code a lot cleaner and easier to work with.
Ex.
Player1.heal(10);

How to properly use methods in Java for Magic 8 Ball program

I have no code to paste since all I have is a template of my methods to be used. Hopefully this isn't too broad because I've looked all over and haven't received the answer I'm needing.
Many have seen or heard of a "Magic 8 Ball" program. A user asks a question, and they receive a random answer in return. I could have written the code easily with one method, but now we've delved into using multiple methods and I'm missing a piece of the puzzle.
The rules of this program:
1) I have to create at least three methods: the main, an input method, and an output method.
2) I have to use a switch statement for the random answers.
3) I have to use a while loop (or a do-while) to prompt the user to either ask another question, or quit.
I think my only problem lies in where to place each piece of the code. I'm going to need to call a Scanner. That's no big deal. I know how to do the switch statement. I know how to randomize the output. I'm most likely going to use a boolean for the keep going/quit part. But where do I actually PLACE the scanner? The boolean? In the main? In an input method? What about the processing section for the randomization? Are all my variables declared in the main so they spread throughout?
I hope my question makes sense.
Creating Scanner once either in main, or in the constructor as a class level object will be much cheaper than creating every time you call the input method. If created at class level it can be used directly in input method, otherwise if it is created in main method it can be passed as an argument to the input method.
Boolean can be in the input method because you are directly comparing the input and you have no more use for it.
When you have an object, especially an expensive one, it is better to create it only once wherever applicable, or create it as few times as possible.
Excuse my sloppy code, and ignore the case names. They are temporary since I will be renaming them. I tried every scenario after compiling. I asked a question, it answered, and it asked if I wanted to ask another. I asked another, it repeated the prompt. I answered "n", and it said "Thanks for playing. Goodbye", and stopped running. Here is my code. Problem solved.
import java.util.Scanner;
public class MagicBall {
public static void main(String[] args) {
int random = 0;
boolean playAgain = true;
while (playAgain) {
askAnother(random);
}//end while
}//end main
public static void askAnother(int r) {
System.out.print("Hello! What is your question? ");
Scanner input = new Scanner(System.in);
String question = input.nextLine();
String yes_or_no;
String next_question;
randomAnswer(r);
boolean playAgain = true;
while(playAgain) {
System.out.println("Would you like to ask another question? Y to ask, N to quit.");
yes_or_no = input.nextLine();
if (yes_or_no.equalsIgnoreCase("Y")) {
System.out.println("What is your next question?");
next_question = input.nextLine();
randomAnswer(r);
}//end if
else if (yes_or_no.equalsIgnoreCase("N")) {
playAgain = false;
System.out.println("Thanks for playing. Goodbye.");
System.exit(0);
}
else {
System.out.println("Invalid Input. Please enter Y or N.");
continue;
}//end else
}//end while
}//end input method
public static int randomAnswer(int r1) {
r1 = (int)(Math.random() * 9);
switch(r1) {
case 0: System.out.println("Yes"); break;
case 1: System.out.println("Yes1"); break;
case 2: System.out.println("Yes2"); break;
case 3: System.out.println("Neutral"); break;
case 4: System.out.println("Neutral1"); break;
case 5: System.out.println("Neutral2"); break;
case 6: System.out.println("No"); break;
case 7: System.out.println("No1"); break;
case 8: System.out.println("No2"); break;
}//end switch
return r1;
}//end output method
}//end MagicBall class

Trouble returning to command options using loops/ only one command is being run (JAVA)

This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.

choice as in int

So far I have written choice as a string but I need to write it to accept int instead of string. The user has to enter 1, 2, 3 and if they enter 1 or 2 the program should continue but if the user enters 3 the program ends.
normally I write the choice as
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
Is there a way to write the code similar to that? I found a way using if statements but that screws up the rest of my code so I'm trying to find a way around that.
Thanks,
it would be better to to this with a so called switch construct
int choice = readInt();
switch(choice){
case 1:
case 2:
// your code
break;
case 3:
// exit code
break;
}
final int STOP_CHOICE = 3;
String choice = "1";
while (Integer.parseInt(choice) != STOP_CHOICE)
{
Note that a non-integer choice will cause Integer.parseInt to throw a NumberFormatException, so you may want to do it somewhere else and catch that possibility.

Categories