public class VoteTUIView {
VoteMachine voteMachine;
public VoteTUIView(VoteMachine voteMachine) {
this.voteMachine = voteMachine;
this.start();
}
public static String errorMissingVariable = "This command needs an variable";
public static String errorPartyNoneExistant = "This party does not exist";
public static String errorAddImpossible = "You can't add something to that";
public static String help = "Seriously? You need help? You look like a smart boy/girl, you can figure this out yourself. I believe in you! ";
public void start(){
System.out.println("Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP) ");
Scanner inputScanner = new Scanner(System.in);
while(inputScanner.hasNextLine()){
String inputCommand = inputScanner.next();
switch (inputCommand){
case "VOTE": {
if(inputScanner.hasNext()){
String inputCommand2 = inputScanner.next();
if(voteMachine.getParties().getParties().contains(inputCommand2)){
voteMachine.vote(inputCommand2);
}
else{
System.out.println(errorPartyNoneExistant);
}
}
else{
System.out.println(errorMissingVariable);
}
}
case "ADD": {
if(inputScanner.next().equals("PARTY")) {
if(inputScanner.hasNext()) {
voteMachine.addParty(inputScanner.next());
}
else{
System.out.println(errorMissingVariable);
}
}
else {
showError(errorAddImpossible);
}
}
case "VOTES": {
showVotes(voteMachine.getVotes().getVoteList());
}
case "PARTIES": {
showParties(voteMachine.getParties().getParties());
}
case "EXIT": {
break;
}
case "HELP": {
System.out.println(help);
}
default: {
}
}
System.out.println("\nPlease insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP) ");
}
}
public void showVotes(Map<String, Integer> voteList) {
int i = 1;
for(String partyName : voteList.keySet()){
System.out.println(i+": "+partyName+" has obtained "+voteList.get(partyName)+" votes.");
i++;
}
}
private void showParties(List<String> partyList) {
int i = 1;
for(String partyName : partyList){
System.out.println(i+": "+partyName);
i++;
}
}
private void showError(String error) {
System.out.println("Error: " + error);
}
}
I am fighting with a strange bug. The program reads the user input and determines which action to take with a switch but often, multiple cases in the switch are triggered when they clearly shouldn't be. It's driving me mad. Does anybody know why it does that?
Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP)
ADD PARTY DemoCant's
1: DemoCant's
Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP)
ADD PARTY RepublicRats
1: DemoCant's
2: RepublicRats
Please insert a command: (VOTE [party], ADD PARTY [party], VOTES, PARTIES, EXIT, and HELP)
VOTE DemoCant's
VOTE DemoCant's
Error: You can't add something to that
1: DemoCant's has obtained 1 votes.
1: DemoCant's
2: RepublicRats
You're missing break statements on almost all switch cases so the code just falls though to the next case. See the section on fall though in the docs
case "VOTE": {
....
break;
}
.....
The cases in a switch statement fall through, and continue executing the next case. If you don't want your case to fall through, add a break; statement and the end of the case. E.g.:
switch (inputCommand){
case "VOTE":
// code for voting
break;
case "ADD": {
// code for adding
break;
// etc...
I am fighting with a strange bug.
Which is why you would have used your debugger before asking a question.
The program reads the user input and determines which action to take with a switch but often, multiple cases in the switch are triggered when they clearly shouldn't be.
since there is no break; or return; there is no reason to break out of the switch.
Note: Java, C, C++, C# all do this.
It's driving me mad. Does anybody know why it does that?
Because that is what it is supposed to do.
You are missing break statement. Without a break statement it is an expected behavior.
You can do more reading about this here http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
add the break statement after each Case
If you don't add a break statement the code flow will go into the next case until all the case ends or till a break is encountered
Related
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.
this accesses an arraylist and there is code that does this same thing already and works fine
is there something wrong with my code here? or a way I can achieve this differently?
System.out.println("Enter cruise ship name: ");
String newCruiseShipName = newCruiseInfo.nextLine();
for(Ship eachShip:shipList) {
if (eachShip.getShipName().equalsIgnoreCase(newCruiseName)){
}
else{
System.out.println("Cruise ship not in service.");
System.out.println("Exiting add cruise");
returnMenu();
}
}
It looks like you are exiting in the first attempt if you cannot find a match based on "Exiting add cruise" line. May be you should also add returnMenu function, so that people can infer what your intention is.
anyways, if this is the case may be you should try something like this:
System.out.println("Enter cruise ship name: ");
String newCruiseShipName = newCruiseInfo.nextLine();
boolean found = false;
for(Ship eachShip:shipList) {
if (eachShip.getShipName().equalsIgnoreCase(newCruiseName)){
found = true;
break;
}
}
if (!found) {
System.out.println("Cruise ship not in service.");
System.out.println("Exiting add cruise");
returnMenu();
}
other possibilities are there can be whitespace in compared strings, or problems with getShipName etc.. may be trim works.
note: could not add comments due to reputation thing
System.out.println("Enter cruise ship name: ");
String newCruiseShipName = newCruiseInfo.nextLine();
if(!newCruiseShipName.contentEquals("")) {
for(Ship eachShip: shipList) {
if(eachShip.getInService()==true||eachShip.getShipName().equalsIgnoreCase(newCruiseShipName)) {
}
for(Cruise eachCruise:cruiseList) {
if(eachCruise.getCruiseShipName().equalsIgnoreCase(newCruiseShipName)) {
System.out.println("Cruise Ship already assigned.");
System.out.println("Exiting add cruise");
returnMenu();
}break;
}
}
}
it was nesting problem I was reducing my array size due to the order the for statements were in previously. I nested them and it solved my problem
I am trying to create an issue tracking System, but I am having a bit of a problem, every time I run the code, it does not come back to the menu, it just loops. I want my code to come back to the menu whenever i describe my issue.
package com.company.TrackingSystem;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
private void menu() {
boolean is = true;
System.out.println("---Menu---");
System.out.println(
"1.Create new Issue\n" +
"2.Mark Issue as solved\n" +
"3.View unsolved Issues\n" +
"4.View solved Issues\n" +
"5.Exit\n"
);
}
}
My tracking class
package com.company.TrackingSystem;
public class TrackingSystem {
private String createIssue;
private boolean issueSolved;
public TrackingSystem(String createIssue, boolean issueSolved) {
this.createIssue = createIssue;
this.issueSolved = issueSolved;
}
public String getCreateIssue() {
return createIssue;
}
public void setCreateIssue(String createIssue) {
this.createIssue = createIssue;
}
public boolean isIssueSolved() {
return issueSolved;
}
public void setIssueSolved(boolean issueSolved) {
this.issueSolved = issueSolved;
}
}
Example output:
---Menu---
1.Create new Issue
2.Mark Issue as solved
3.View unsolved Issues
4.View solved Issues
5.Exit
Select option >> 1
*** Create an Issue***
Describe your Issue:
*** Create an Issue***
Describe your Issue:
as
*** Create an Issue***
Describe your Issue:
sa
*** Create an Issue***
Describe your Issue:
as
Let's look at this function:
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
Pay special attention to the loop condition: while(is). You declare bool is = true; but you never change it to false inside the loop. This means the loop will continue forever.
To fix this, you have to make some decisions. First, do you really want to continue looping here? Is your intention to allow the user to enter as many issues as they want? Or do you want to create only a single issue then return to the menu. If the former, then you need to figure out how the user will tell the program that they are finished entering issues. You can use this to stop the loop. If the later, then just remove the loop.
Now let's look at main():
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
Even after you solve the problem with your code to create an issue, you will run the program and it will exit after one action. This is because you do not loop in main(). You need to add a loop here that repeats the following steps:
Print the menu.
Get the user's choice.
Perform the action for that choice
Repeat to step 1.
Each of these steps can be a method so that you can keep main() very short. Note how the first 3 steps are inside a loop. I think this is what you were trying to do with the loop for creating a new item, but somehow put the loop in the wrong place. As you can see here, by writing out the steps in words, we get a clear idea of how to organize the code. Doing this is a great tool when writing a computer program.
I'm a beginner at Java and I want to get into it and I enjoy playing around with it. So I started doing an online course.
So after a few videos I learned a bit about switch statements and wanted to know how to loop them effectively.
package v1;
import java.util.Scanner;
public class Computer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Computer is booting up...");
System.out.println("Welcome to Mindows '93, please enter a command.");
String command = input.nextLine();
boolean computerON = true;
while (computerON) {
switch (command) {
case "!music":
System.out.println("Playing music!");
break;
case "!browse":
System.out.println("Launching browser...");
break;
case "!help":
System.out.println("Here are the commands that can be used !music, !browse, !shutdown");
break;
case "!shutdown":
System.out.println("Shutting down Mindows, goodbye!");
break;
default:
System.out.println("Command not recognised, type !help for a list of commands...");
break;
}
if (command.equals("!shutdown")) {
computerON = false;
}
}
}
}
So basically what I want is to make a mock text-based OS called Mindows with very limited functionality, but I'm having problems.
When I input !music, the program will constantly spam lines of "Playing music!"
When I enter !shutdown, however, it terminates which is what I want.
What I want is to type !music, !browse, !help and (x) to get the default message without the program spamming lines OR terminating.
I want to be able to type these commands in constantly until the !shutdown command is issued.
You read the command only once, out of your loop.
Try moving the line:
String command = input.nextLine();
into the while loop.
You're going into an infinite loop because you are accepting input from the user before the loop, and the input doesn't change during the execution of the loop. So if you entered "!music", the command doesn't change throughout the loop and the switch statement always goes into case "!music": in each iteration of the loop, which is why computerON is always true and the loop executes and prints "Playing music" infinitely.
The solution to this would be to move the String command = input.nextLine(); statement inside the while loop, like the above answers say.
Changed your logic here :
boolean computerON = true;
while (computerON) {
String command = input.nextLine();
switch (command) {
case "!music":
System.out.println("Playing music!"); break;
case "!browse":
System.out.println("Launching browser...");
break;
case "!help":
System.out.println("Here are the commands that can be used !music, !browse, !shutdown");
break;
case "!shutdown":
System.out.println("Shutting down Mindows, goodbye!");
break;
default:
System.out.println("Command not recognised, type !help for a list of commands...");
break;
}
if (command.equals("!shutdown")){
computerON = false;
}
}
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