(beginner) How to use a switch statement with strings? - string

I'm trying to make a simple bank account program to learn classes and OOP. As you may guess, I'm new to Java.
Anyways, my switch statement is not working. I'm trying to make each case based on an inputted string.
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
//the user enters "user1", "user2", or "user3".
String user = input.next();
//swtich time
switch (user) {
case "user1":
System.out.println("Your balance is" + user1.balance);
System.out.println("Your Account numer is" + user1.acctnum);
//shows the balance and account number for user1
case "user2":
System.out.println("Your balance is" + user2.balance);
System.out.println("Your Account numer is" + user2.acctnum);
case "user3":
System.out.println("Your balance is" + user3.balance);
System.out.println("Your Account numer is" + user3.acctnum);
}

You're missing a break statement at the end of each case.
case "user1":
System.out.println("Your balance is" + user1.balance);
System.out.println("Your Account numer is" + user1.acctnum);
//shows the balance and account number for user1
break;
Without the break statement, all of these statements will be executed
Docs

You can use Strings in switch statements if you are using Java 7 or above, otherwise you can't

You can enumerate the string, and then use switch.
P.S: Please search around a bit and then post questions here ;) Your question is similar to this one (for ex - there are plenty of answers out there)
https://stackoverflow.com/a/338284/878170

You are missing break; statement and hence all statements after selected case will be executed.
Here's an example of switch-case [1]
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
[1] http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

Related

Why is this switch statement only returning the default?

switch (numYears) {
case 10:
intsRate = 0.06;
break;
case 15:
intsRate = 0.05;
break;
case 30:
intsRate = 0.04;
break;
default:
intsRate = 0.08;
break;
}
return intsRate;
}
when the input of numYears is 10, 15, or 30 its returns the according double, but its only returning the defult. its part of a larger code but everything in that code is right this is the only part returning the wrong thing.

JAVA Switches, if then else and booleans with string

I'm having a bit of trouble getting a few parts of my code to work properly.
I'm still a bit new to java and could some direction and clues to where I went wrong.
The error comes from the if statements. I feel like i know why they are erring out because the || are undefined but I'm not sure how to fix it. What I'm trying to get it to do is take the inputs either L,R,F,B (left, right, forward and back). lowercase the input and either accept either one or the other using boolean "or".
import java.util.Scanner;
public class ChooseYourAdventure {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Choose a diection: ");
String direction = input.nextLine().toLowerCase();
System.out.printf(" %s and %s/n",getDirection (way),getYourChoice (found));
}
public static String getYourChoice (String found) {
String result = "Unknown";
switch (found)
{
case "l":
result = " now we all know you can turn left unlike Zoolander";
break;
case "left":
result = " now we all know you can turn left unlike Zoolander";
break;
case "r":
result = " you fall down a hole never to be seen again... sad.";
break;
case "right":
result = " you fall down a hole never to be seen again... sad.";
break;
case "f":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "forward":
result = " YOU ARE THE KWISATZ HADERACH!!";
break;
case "b":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
case "back":
result = " you are a scaredy cat but, you live to fight or runaway another day";
break;
}
return result;
}
public static String getDirection(String way) {
String result;
if (way == "l" || "left") {
System.out.print("Your character moves left");
}
else if (way == "r" || "right") {
System.out.println("You character moves right");
}
else if (way == "f" || "forward") {
System.out.println("Your character moves forward");
}
else if (way == "b" || "back") {
System.out.println("Your character moves forward");
}
else {
System.out.println(" You cant go that way ");
}
return result;
}
}
All your if statements are wrong. When using || or &&, you need to specify the variable way on each side of the ||:
if (way == "l" || way == "left") {
System.out.print("Your character moves left");
}

Stuck on virtual zoo

I'm doing a virtual zoo in computer science and i'm stuck. We are using a guide to navigate through the zoo, but I can't figure out how to go without getting errors. When I run it it says "Null! Null, and I have no idea what to do. I am pretty new to coding so thank you for your help.
class Guide {
private String name;
int Selection;
int Selection1;
int Selection3;
int Selection2;
int choice;
Scanner inputScanner = new Scanner (System.in);
void welcomeusertozoo() {
System.out.println("Hello! Welcome to Cringe Jarin! A Zoo full of cringy creative creatures. Im Fred. What is your Cringy Name?");
name = inputScanner.next();
System.err.println("Ewww..... How cringy. Well, Welcome " + name + "! What creatures would you like to visit First?"
+ "\n 1.Ogres"
+ "\n 2.Vampires"
+ "\n 3.Rats \n\n" );
choice = inputScanner.nextInt();
creatureselection(choice);
}
void creatureselection(int Selection) {
switch (Selection) {
case 1: System.out.println("Plug up the nose and close those eyes! These creatures are Ugly! who Would you Like to visit...\n Please press 1 to go meet the commander himself, Ogre E Lee. \n Please press 2 to go meet the one and only Ogrewall Jackson. \n Please press 3 to meet the wonderful Mr.GreenBean. \n Please press 4 to meet the rebellious William Shrallace. \n\n");
choice = inputScanner.nextInt();
switch (choice){
case 1: System.out.println("Commander Ogre. E Lee Here! \n\n");
case 2: System.out.println("This is the impeccable, the amazing, one and only Ogrewall Jackson \n\n");
break;
case 3: System.out.println("This is the fashionable, the sexy, the fabulous GreenBean \n\n");
break;
case 4: System.out.println("This is the free, the bravest heart I know, the impecable William Shrallace \n\n");
default: System.out.println("We do not have a creature under that selection at the moment. Please choose 1 or 2 or 3 \n\n");
}
break;
case 2:System.out.println("Dont have a scarf? Oh.... watch your necks! Who would you like to visit...\n Please press 1 to go meet the spooky Dio. \n Please press 2 to go meet the truly bone chilling Diego. \n Please press 3 to meet the bloodthirsty Big White Bat. \n Please press 4 to meet the Bold Mubat. \n\n");
choice = inputScanner.nextInt();
switch (choice){
case 1: System.out.println("Dio \n\n"); creatureselection(2);
break;
case 2: System.out.println("Diego \n\n"); creatureselection(2);
break;
case 3: System.out.println("Big White bat \n\n"); creatureselection(2);
break;
case 4: System.out.println("Bold Mubat \n\n"); creatureselection(2);
break;
default: System.out.println("We do not have a creature under that selection at the moment. Please choose 1 or 2 or 3 \n\n");
creatureselection(2);
}
break;
case 3:System.out.println("Pull out the Cheese but dont let it rip! These creatures are Cringy! Who would you like to visit...\n Please press 1 to go meet the Odd Ratty Weisau. \n Please press 2 to go meet the backstabbing Risa. \n Please press 3 to meet the permanently sad Dindin. \n Please press 4 to meet the sketchy Markymouse. \n\n");
choice = inputScanner.nextInt();
switch (choice) {
case 1: System.out.println("Ratty Weisau \n\n"); creatureselection(3);
break;
case 2: System.out.println("Risa \n\n"); creatureselection(3);
break;
case 3: System.out.println("Dindin \n\n"); creatureselection(3);
break;
case 4: System.out.println("Markymouse \n\n"); creatureselection(3);
break;
default: System.out.println("We do not have a creature under that selection at the moment. Please choose 1 or 2 or 3 \n\n");
creatureselection(3);
}
break;
default: System.out.println("We do not have a creature under that selection at the moment. Please choose 1 or 2 or 3 \n\n");
creatureselection(1);
}
}
void setName(String fred) {
}
}
What seems to be the problem?
Can you provide more information on what is the problem.
It seems to be working.
Are you creating a Guide object?
public class test {
public static void main(String[] args) {
Guide guide = new Guide();
guide.welcomeusertozoo();
}
}
After that everything seems to be working.
Just make sure that you have breaks on every case, just to assure consistency.
Hope I've helped.
This is the main :
public class ZooProject {
public static void main(String[] args) {
Rat RattyWiseau = new Rat ();
Ogre OgreELee = new Ogre();
Vampire Dio = new Vampire ();
Guide Fredtheguide = new Guide ();
//ask user for name
RattyWiseau.setName("Ratty Wiseau");
Dio.setName("Dio");
// Fredtheguide.setName("Fred");
OgreELee.setName("Ogre E Lee");
Fredtheguide.welcomeusertozoo();
System.out.println(OgreELee.getName());
}
}

Jcombobox and switch case

I want to link my combobox selected item with switch case which result in different result depend on option chosen. But return in this error :Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JComboBox cannot be cast to java.awt.event.ItemListener. Can only one help me, thanks you so much!
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1.addItemListener((ItemListener) jComboBox1);
int usertype = (int) jComboBox1.getSelectedIndex();
switch (usertype) {
case '1':
new ResidentView().setVisible(true);
this.dispose();
break;
case '2':
new OfficeClerkView().setVisible(true);
this.dispose();
break;
case '3':
new OfficeManagerView().setVisible(true);
this.dispose();
break;
}

Default statement position in switch

switch(2){
default : System.out.println("I am Default block");
case 1 : System.out.println("in 1");
case 2 : System.out.println("in 2");
}
The output : in 2
and if
switch(2){
case 1 : System.out.println("in 1");
case 2 : System.out.println("in 2");
default : System.out.println("I am Default block");
}
And the output is: in 2
I am Default block.
Does the positioning of the default statement behaves differently?
It's not the position of the default block, it's the use (or non-use in your case) of the break statement.
Once a case has been matched, the default behaviour is for the code to cascade through the rest of the cases.
To achieve the behaviour you desire, try
switch (2)
{
case 1:
System.out.println("in 1");
break;
case 2:
System.out.println("in 2");
break;
default:
System.out.println("I am Default block");
break;
}
Kathy Siera SCJP book do say that position of default: matters and if present in between the case statements, it follows the fall-through.
But practically it does not follow.
int a = 10;
switch (a)
{
case 5:
System.out.println("Its 5");
default:
System.out.println("Its default");
case 10:
System.out.println("Its 10");
case 20:
System.out.println("Its 20");
}
Output:
Its 10
Its 20

Resources