Switch Variables Depending on If Statement - java

I'm trying to create a program where it switches the variables depending on, in this case, as an example, what animal you've chosen. Without having to use the print command twice.
For example. I created two strings:
String thingsForDogs = "bone";
String thingsForCats = "yarn";
And those strings would switch with each other, when printing out the result, depending on what the user chose as an animal. I don't know how I would code this, but if the user chose Cat as their animal, they would get a different output than if they've chosen Dog.
I know I could do something like this:
System.out.println("What animal do you want to be? Dog or cat?");
Scanner kb = new Scanner(System.in);
char choice = kb.nextLine().charAt(0);
if(choice == 'c' || choice == 'C')
System.out.println("You have " + thingsForCats);
else if(choice == 'd' || choice == 'D')
System.out.println("You have " + thingsForDogs);
But I still don't know how I could do it, without having to repeat the print command. I'm trying to print it all in one print command, but the variable along with it being printed, is switched, depending on what the user chose as their animal.

There is nothing wrong with your code.
You may change it wo a swich:
System.out.print("You have ");
switch(choice){
case "c":
case "C":
System.out.println(thingsForCats);
break;
case "d":
case "D":
System.out.println(thingsForDogs);
break;
default:
// some errorhandling or Stuff
}

You could use a HashMap to store that data and avoid the if-statement all together.
HashMap<char, String> map = new HashMap();
map.add('c', "yarn");
map.add('d', "bone");
...
// convert the input to lower case so you don't have to check both lower
// and upper cases
char choice = Character.toLowerCase(kb.nextLine().charAt(0));
System.out.println("You have " + map.get(choice));

There you have, one line printing
String thingsForPet = "";
System.out.println("What animal do you want to be? Dog or cat?");
Scanner kb = new Scanner(System.in);
char choice = kb.nextLine().charAt(0);
thingsForPet = Character.toLowerCase(choice) == 'c' ? "yarn" : "bone";
System.out.println("You have " + thingsForPet);
Considering your comment you can change last 2 lines as:
if(choice == 'c' || choice == 'C') {
thingsForPet = "yarn";
}
else {
thingsForPet = "bone";
}
System.out.println("You have " + thingsForPet);

Related

Why does System.out.println(String) not print anything?

I have some code in my java IDE and I believe that it has support for console. I have used java before and know the ins and outs. However, this problem has not occured with me before. My code looks like this:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
System.out.println("Choose a class.");
TimeUnit.SECONDS.sleep(10);
System.out.println("Press 1 for the a class.");
TimeUnit.SECONDS.sleep(10);
System.out.println("Press 2 for the b class.");
TimeUnit.SECONDS.sleep(10);
System.out.println("Press 3 for the c class.");
TimeUnit.SECONDS.sleep(10);
switch(choice) {
case 1:
playerClass.chosenClass = "a";
break;
case 2:
playerClass.chosenClass = "b";
break;
case 3:
playerClass.chosenClass = "c";
break;
default:
System.out.println("Null class. Please press 1-3 to choose a player class.");
}
}
I have all the imports, and the playerClass class does exist. The problem is, the "System.out.println(String)"'s do not work.
You're printing the prompt after accepting the input. And as you haven't seen the prompt yet, you probably aren't typing any input. So you never get past Scanner.nextInt().
Your code doesn't make sense.
What you might want to do is set your logic more like:
System.out.println("Press 1 for xx, 2 for xx, or 3 for xx");
if(scanner.hasNext()){
choice = scanner.Int();
}
if(choice == 1){
//do whatever;
}
else if(choice == 2){
//do whatever;
}
I might not be understanding your question right but I think you need to make sure you keep everything in order.

Check whether switch case is chosen [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have an exercise that using switch case. Assuming the code like
int choice;
do {
choice = //user input here;
switch (choice) {
case 1: //print something; break;
case 2: //print something; break;
case 3: //print something; break;
default: //print default; break;
}
} while(condition);
i want the user can only choose the case once. If they did choose case 1, they cannot choose that again.
Define a private bool variable for each one of your options and set it true if user called each one. Then check whether its true before running that option codes, again.
For example:
bool _case1=false;
int choice;
do{
choice = //user input here;
switch(choice){
case 1:
if(!_case1)
{
//print something;
_case1=true;
}
else
{
//Tell the user "You have selected this option once"
}
break;
//etc
}
}while(condition);
You could call methods for each case and have some bools that mark whether each case has already been chosen, use an if statement to check if the case has already been chosen and if so print a notice to pick another, otherwise perform the action.
You could also do this without separate methods but I am a fan of modular code. :)
I am assuming that a function that contains this switch case is called over and over again. If you want such a functionality, I would point to Set. Use the set to store the choices. If a set already contains a certain choice, take whatever action you deem fit.
Using a set is better than having a global array of booleans, since that could potentially be wasting a lot of memory, depending on the number of choices that you have.
Does that answer your question?
When user press the input
if the input is match case then
store this input in one List.
Next time you have to check this input.
If it belongs in List or not,
if belongs then case will not execute
if not belongs then it will execute the case.
Try in this way :
List<Integer> choiceList = new ArrayList<Integer>();
int choice;
do {
choice = //user input here;
if (choiceList.contains(choice)) {
continue;
}
choiceList.add(choice);
switch(choice) {
case 1: //print something; break;
case 2: //print something; break;
case 3: //print something; break;
default: //print default; break;
}
} while(condition);
As some of the other answers have said you can use a boolean to check if a case has been used or not. However, you can also use an int. The advantage of using an int is that you can specify how many times each case can be used. For example, the following code can only use each case once.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int choice;
int case1 = 0, case2 = 0, case3 = 0;
int case1lim = 1, case2lim = 1, case3lim = 1;
System.out.println("You may use may enter the number 1 " + case1lim + " times");
System.out.println("You may use may enter the number 2 " + case2lim + " times");
System.out.println("You may use may enter the number 3 " + case3lim + " times");
do {
System.out.println("Please enter a number between 1 and 3");
choice = user_input.nextInt();
if(choice == 1 && case1 < case1lim || choice == 2 && case2 < case2lim || choice == 3 && case3 < case3lim) {
switch(choice){
case 1: //print something;
case1++;
break;
case 2: //print something;
case2++;
break;
case 3: //print something;
case3++;
break;
default: //print default;
break;
}
} else {
System.out.println("Please pick another number since you have already used that case or you entered a bad value");
}
} while(true);
}
}
However if you change the values of the line
int case1lim = 1, case2lim = 1, case3lim = 1;
to
int case1lim = 2, case2lim = 1, case3lim = 1;
You can use the first case twice and all the other cases once.

How can i get it where if i enter "e" for sales figure and "r" for random? Not able to figure out how [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 8 years ago.
int store1, store2, store3, store4, store5;
char ans = 'e';
String gen;
Scanner scan = new Scanner(System.in);
Random randNum = new Random();
System.out.println("Do you want to enter the sales figure (e) or do you want it randomly generated (r)? ");
gen=scan.nextLine();
if (ans == 'e' || ans == 'E')
{
System.out.println("Enter todays sales for: ");
System.out.println("Store 1: ");
store1=scan.nextInt();
System.out.println("Store 2: ");
store2=scan.nextInt();
System.out.println("Store 3: ");
store3=scan.nextInt();
System.out.println("Store 4: ");
store4=scan.nextInt();
System.out.println("Store 5: ");
store5=scan.nextInt();
scan.close();
}
else
{
System.out.println("Store 1: ");
store1=randNum.nextInt(10);
System.out.println("Store 2: ");
store2=randNum.nextInt(10);
System.out.println("Store 3: ");
store3=randNum.nextInt(10);
System.out.println("Store 4: ");
store4=randNum.nextInt(10);
System.out.println("Store 5: ");
store5=randNum.nextInt(10);
}
}
}
Need to figure out how to get this code working properly. Right now it only recognizes the 'e' and 'E' enter but not if i enter anything else. When it does do the else the random number gen won't work.
Look at this part of your code
gen=scan.nextLine();
if (ans == 'e' || ans == 'E')
You are reading in gen, but comparing ans, this can't work.
change your statement to
if (gen.toUpperCase().charAt(0) == 'E')
Also, I smell that you are about to compare String, and I smell that you maybe don't know how as you stated I'm a beginner in progress.
So note that if you want to compare String, you need to use the .equals method as if you use == you will compare memory address (as for any other Object)

Unable to compare Char / String? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
What I want to do is simply read a input (Char/String , preferably char), its a single char and then print some outputs based on the inputs. My problems faced is that, if i convert my input 'choice' into a char, my error messages are:
Type mismatch: cannot convert from String to char
Incompatible operand types char and String
any idea whats wrong? Thanks!
*If I leave it like this it just gives me "Invalid Choice"
import java.util.*;
public class P1 {
public static void main(String[] args) {
// Create a scanner
Scanner userInputScanner = new Scanner(System.in);
String choice = userInputScanner.nextLine();
System.out.println("Your choice is " + choice);
if ((choice == "A") || (choice == "a"))
System.out.println( " Action Movie Fan");
else if ((choice == "C") || (choice == "c"))
System.out.println( " Comedy movie fan ");
else if ((choice == "D") || (choice == "d"))
System.out.println(" Drama movie fan ");
else
System.out.println( "Invalid choice" );
}
}
You compare strings in Java using equals:
if ("A".equals(choice) || "a".equals(choice)) {
...
}
or equalsIgnoreCase:
if ("A".equalsIgnoreCase(choice)) { // "a".equalsIgnoreCase(choice) works too
...
}
However, in your case you need to compare a single character, so you can do this:
if (choice.length() == 1) {
// Convert to upper case for case insensitivity
char selection = Character.toUpperCase(choice.charAt(0));
switch (selection) {
case 'A':
...
break;
case 'C':
...
break;
case 'D':
...
break;
}
...
}
For your case, try to use String.equalsIgnoreCase.
You might want to explore usage of Enum as well.
import java.util.*;
public class P1 {
public static void main(String[] args) {
// Create a scanner
Scanner userInputScanner = new Scanner(System.in);
String choice = userInputScanner.nextLine();
System.out.println("Your choice is " + choice);
if (choice.trim().equalsIgnorecase("A"))
System.out.println( " Action Movie Fan");
else if (choice.trim().equalsIgnorecase("B"))
System.out.println( " Comedy movie fan ");
else if (choice.trim().equalsIgnorecase("D"))
System.out.println(" Drama movie fan ");
else
System.out.println( "Invalid choice" );
}
}
otherwise compare only first character of string like choice.charAt(0) == 'A'
What you should know is that "A" and "a" are not chars, they are Strings. What you should do is call String's equals() (and not the == operator) method to compare. Just like that:
if(stringOne.equalsIgnoreCase("A")) {
//methods
}

How would I create a "infinite" loops until the user decides to call it quits?

I'm having a slight problem.
I have a menu asking to:
reroll
get val
show max
show min
when the user chooses an option I want it to do one of them THEN re ask the menu in a sort of inifinite loop:
code:
import java.io.InputStream;
import java.util.Scanner;
class RecordDice {
public static void main(String[] args){
int dSides, Sides, Choice;
int max, min;
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
System.out.println("How many sides should the dice have?");
Sides = s.nextInt();
if(Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100){
System.out.println("Please make a choice:\n" +
"1 - reroll the dice\n" +
"2 - get the value\n" +
"3 - show the maximum\n" +
"4 - show the minimum");
} else {
System.exit(-1);
}
Dice2 d = new Dice2(Sides);
int Choice = c.nextInt();
int Value = d.getValue();
switch(Choice){
case 1:
System.out.println();
d.reroll();
break;
case 2:
System.out.println("The current value is " + Value);
break;
case 3:
System.out.println("The maximum is " );
break;
case 4:
System.out.println("The minimun is ");
break;
}
}
}
Would putting the menu in a method and just calling the method every time a option is picked?
You can use a while loop to keep displaying it.
boolean keepGoing = true;
While(keepGoing)
{
//your code
}
Then to end it ask the user if they want to end it an set the boolean to false.
Add "5 - quit" to your menu.
Create a boolean, something like exit, initialized to false.
Add case 5: exit = true; break;
Then wrap the whole thing in while(!exit)
boolean exit = false;
while(!exit) {
//all the code you already have, starting with:
System.out.println("How many sides should the dice have?");
//and ending with the switch statement
//Plus the addition to the menu and addition to the switch statement
}
Ordinarily, I would do something like:
while(true) {
//do stuff
if(someExitCondition) {
break;
}
}
But seeing how as you're handling your user input with a switch statement, my above suggested method seems to be the cleanest way of handling it in this scenario.
Wrap it all in a do-while loop.
boolean userWantsToQuit = false;
do {
// code
// evaluate userWantsToQuit…
} while (!userWantsToQuit);
boolean keepGoing=true;
while(keepGoing)
{
//user input
if(user input to exit)
{
keepGoing=false;
}
}
or
while(true)
{
//user input
if(user input to exit)
{
break;
}
}
Assuming selection of dice sides you will allow only once, put code below that in do while loop.
You may prompt user "Do you wish to continue" after your switch block.
Get that value scanned
Condition in while loop will be something list while("YES".equals(userInput)).. assuming user will input YES or NO strings.

Categories