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
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 have a question as to how I can perform several checks inside the switch-case? I need to do a couple of checks in case 2, but adding a second if block, my application does nothing, it just hangs. What was I wrong about?
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
if (inputCommand.readLine().equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
if (inputCommand.readLine().equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
In the second case statement, you should read the next input only once:
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
String next = inputCommand.readLine();
if (next.equals("su")) {
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (next.equals("an")) {
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
}
Your first if statement is swallowing the input line, so the second if statement has nothing to read.
Just store the line after reading it once :
String readLine = inputCommand.readLine();
if (readLine.equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (readLine.equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
Everytime you do a inputCommand.readLine() the Programm waits for an input on your side. You can't compare a single input like you did in this example. The best way would be to save the input in a variable and then perform your checks. Something like this would work (not tested):
BufferedReader inputCommand = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.println("Instruction:");
System.out.println();
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println();
switch (inputCommand.readLine()) {
case "1":
basketCommand.get();
System.out.println();
break;
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
String input = inputCommand.readLine();
if (input.equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
if (input.equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
}
Replace if with else if
case "2":
System.out.println();
System.out.println("Select product to add into your basket");
if (inputCommand.readLine().equals("su")){
basketCommand.addIntoBasket(productContainer.productList.get("su"));
}
else if (inputCommand.readLine().equals("an")){
basketCommand.addIntoBasket(productContainer.productList.get("an"));
}
break;
I assumed this is a basic program for learning purposes so i tried to keep it simple.
1.Don't forget to close Scanner class.
2.always convert digit input to LowerCase(consider case of 'q' vs 'Q')
3.everytime you execute "scanner.nextLine()" your program will halt and wait for input from source(in that case System.in configured to take input from keyboard)
4.System.out.println will print '\n' to the screen at the end of its input causing it to create a new line, you can use this char inside your string to save code lines.
Complete Code:
import java.util.Scanner;
import java.io.IOException;
public class MyClass {
public static void ShowMenu()
{
System.out.println("\nInstruction:");
System.out.println("1 -- Show all product at the store");
System.out.println("2 -- Add the product at the client basket");
System.out.println("3 -- Show client basket");
System.out.println("q -- Quit Program");
}
public static void ProductMenu()
{
System.out.println("Select product to add into your basket");
System.out.println();
System.out.println("ba -- Basketball");
System.out.println("fi -- Fiat 500");
System.out.println("ip -- Iphone");
System.out.println();
}
public static void Exit(Scanner sc) {
sc.close();
System.out.println("You've exited the program. goodbye!");
System.exit(1);
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
String inputCommand = null;
while (true) {
ShowMenu();
switch (inputCommand = scanner.nextLine().toLowerCase()) {
case "1":
System.out.println("you entered 1");
break;
case "2":
ProductMenu();
inputCommand = scanner.nextLine(); //should block
if (inputCommand.equals("ba")){
System.out.println("Basketball added.");
}
if (inputCommand.equals("fi")){
System.out.println("Fiat 500 added.");
}
if (inputCommand.equals("ip")){
System.out.println("Iphone added.");
}
break;
case "q":
Exit(scanner);
break;
default:
System.out.println("Invalid Input");
break;
}
}
}
}
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);
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).
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)