Working on this for a school assignment, and confused about how switches and cases work. I thought I finally got it to work, but I am still getting a formatting error, and I'm not sure why.
import java.util.Scanner;
public class PartyAffiliation
{
public static void main(String[] args)
{
do
{
String Party = null;
boolean running = true;
Scanner in = new Scanner(System.in);
loopParty: while(running)
{
System.out.println("What is your politcal party? (D for Democrat - R for Republican - I for Independent");
Party = in.nextLine();
switch (Party)
{
case ("D"):
System.out.println("You get a Democratic Donkey!");
running=false;
break;
case ("R"):
System.out.println("You get a Republican Elephant!");
running=false;
break;
case ("I"):
System.out.println("You get an Independent Man!");
running=false;
break;
default:
System.out.println("I guess you aren't any of the three.");
break;
}
}
}
}
}
You don't need a boolean sentinel like running. And you can't have a raw do block (without a while, which you really don't need). Use an infinite loop, label it and then you can break on that label. Also, it's better (IMO) to allow mixed case input (so I would call toUpperCase() on the input). Like,
String party = null; // <-- follow Java naming conventions. Party looks like a Class.
Scanner in = new Scanner(System.in);
loop: while (true) {
System.out.println("What is your politcal party? (" +
"D for Democrat - R for Republican - I for Independent");
party = in.nextLine();
switch (party.toUpperCase()) {
case "D": // <-- you don't need () around your case values
System.out.println("You get a Democratic Donkey!");
break loop;
case "R":
System.out.println("You get a Republican Elephant!");
break loop;
case "I":
System.out.println("You get an Independent Man!");
break loop;
default:
System.out.println("I guess you aren't any of the three.");
}
}
If I understand your intent correctly, perhaps you want to do this:
public static void main(String[] args) {
String Party = null;
boolean running = true;
Scanner in = new Scanner(System.in);
do {
System.out.println("What is your politcal party? (D for Democrat - R for Republican - I for Independent");
Party = in.nextLine();
switch (Party) {
case ("D"):
System.out.println("You get a Democratic Donkey!");
running = false;
break;
case ("R"):
System.out.println("You get a Republican Elephant!");
running = false;
break;
case ("I"):
System.out.println("You get an Independent Man!");
running = false;
break;
default:
System.out.println("I guess you aren't any of the three.");
break;
}
} while (running);
}
do should come with matching while. You want to keep asking for input from user until they enter a valid input (i.e. D, R, or I).
Related
I am trying to write a program that receives the number of sides from the
user and determines the type of figure using switch structure and a while sentinel-controlled loop, but every time I get an infinite loop. How can that be fixed?
import java.util.Scanner;
public class P1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the number of sides:");
int s = input.nextInt();
while ( s!=-1)
{
switch (s)
{
case 1: System.out.println("Line");
break;
case 2:System.out.println("Angle");
break;
case 3:System.out.println("Triangle");
break;
case 4:System.out.println("Quadrilateral");
break;
case 5:System.out.println("Pentagon ");
break;
case 6:System.out.println("Hexagon");
break;
case 7:System.out.println("Heptagon");
break;
case 8:System.out.println("Octagon");
break;
case 9:System.out.println("Nonagon");
break;
case 10:System.out.println("Decagon");
break;
default: System.out.println("Enter a valid value:");
}
}
}
}
The while loop is written to continue as long as s!=-1; so you need to change s so that this expression is no longer true.
I am trying to make my rock paper scissors app loop if the user wants it to and am not sure how.
I am in a programming class but I broke my code while trying to fix it last time and managed to return to what I had before.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String playAgain = "Y";
while (playAgain.equals("Y") || playAgain.equals("y"))
{
String playerChoice = "";
while (!playerChoice.equals("R") && !playerChoice.equals("P") && !playerChoice.equals("S"))
{
System.out.println("Please enter a correct character\n (R)ock, (P)aper, or (S)cissors.");
playerChoice = scan.next();
//Player choice to upper case to minimize the number of wrong inputs//
playerChoice = playerChoice.toUpperCase();
}
int randNum = (int) (Math.random() * 3);
String compChoice = "";
switch (randNum)
{
case 0:
compChoice = "R";
break;
case 1:
compChoice = "P";
break;
case 2:
compChoice = "S";
break;
}
System.out.println("The computer chose: " + compChoice);
if (playerChoice.equals(compChoice))
{
System.out.println("It's a Tie!");
} else if (playerChoice.equals("R") && compChoice.equals("S") || playerChoice.equals("P") && compChoice.equals("R") || playerChoice.equals("S") && compChoice.equals("P"))
{
System.out.println("You Win!");
} else
{
System.out.println("You Lose");
}
System.out.println("Would you like to play again?\n(Y or N)");
playAgain = scan.nextLine();
if (playAgain.equals("N"))
{
break;
}
}
}
The solution is you need agreement between your scan method calls.
Either both should be nextLine or both should be next.
As an aside - I quite like the use of .equalsIgnoreCase instead of .equals on string comparisons, since it makes the code simple and easy to read. (You can skip the toUpperCase for instance, and the extra conditions)
As for why/what exactly the scanner is doing which causes that problem, that's a lot more detailed and fiddly.
import java.util.Scanner;
class MenuFastFood {
public static void main(String[] args) {
String s;
char order;
Scanner keyboard = new Scanner(System.in);
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);
do {
switch(order) {
case 'A':
System.out.println("CheeseBurger");
System.out.println("Onion Rings");
System.out.println("Soda");
break;
case 'B':
System.out.println("Hot dog");
System.out.println("Fries");
System.out.println("Milk Shake");
break;
default:
System.out.println("error");
return;
case 'X':
System.out.println("EXIT");
break;
}
}while(order != 'X');
}
my program is suppose to pick an item based on the character enter in to keybaord and then loops back if another item is selected. when i run this and pick an item. it loops that item for ever. How do i get that to stop and makes it able for me to select another item?
Move your code for reading input to inside do..while
s = keyboard.next();
s = s.toUpperCase();
order = s.charAt(0);
I've been playing around with basic Java and begun to create a project which includes a user input, system output ad a switch/case statement too. The user inputs a given animal and the system outputs the necessary noise that relates to the animal. At the moment the program asks the user once and then it is finished, however I want the user to be able to input as many animals as they'd like and get appropriate responses. Any help welcome, thanks. (I understand there may be some errors in my code, but I have only really just begun Java.)
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
String myString;
System.out.println("Enter your first animal: ");
myString = user_input.next();
loop: switch (myString) {
case "Cow":
System.out.println("Mooo!");
break;
case "Sheep":
System.out.println("Baaaa!");
break;
case "Mouse":
System.out.println("Squeak Squeak!");
break;
case "Horse":
System.out.println("Neighhh!");
break;
case "Goat":
System.out.println("Skreachh!");
break;
case "Fish":
System.out.println("*Bubble Bubble*");
break;
default:
System.out.println("Invalid animal.");
break;
}
}
You need a loop and a condition to stop.
while (true) {
...
switch(...) {
....
case "Stop":
System.out.println("bye bye");
System.exit(0);
break;
}
}
You can also use do-while loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter your first animal: ");
myString = input.next();
switch (myString) {
case "Cow":
System.out.println("Mooo!");
break;
........
default:
System.out.println("Invalid animal.");
break;
}
} while (!myString.equals("Stop"));
}
You can get a well-explanation from here and here
So I need the statements inside the while loop to repeat until the user enters 4 (which exits the program), but when I try to run the program, nothing is outputted to the screen (but it compiles just fine). Why would it do this? This answer is probably really simple, but any help would be really appreciated!
public class Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int answer;
boolean bool = true;
while(bool);
{
System.out.println("\n\tGeometry Calculator\n" +
"\t1. Calculate the Area of a Circle\n" +
"\t2. Calculate the Area of a Rectangle\n" +
"\t3. Calculate the Area of a Triangle\n" +
"\t4. Quit\n");
System.out.print("\tEnter your choice (1-4): ");
answer = keyboard.nextInt();
switch(answer)
{
case 1:
System.out.println("\n\tCalculating the area of a circle...");
break;
case 2:
System.out.println("\n\tCalculating the area of a rectangle...");
break;
case 3:
System.out.println("\n\tCalculating the area of a triangle...");
break;
case 4:
System.out.println("\n\tQuiting...");
System.exit(0);
break;
default:
System.out.println("\n\tPlease enter a number between 1 and 4.");
}
if(answer == 4)
bool = false;
}
}
You have one tiny mistake. You have added ; after the while loop. Just delete it. Your code should be
while(bool)