Domanda

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);
}
È stato utile?

Soluzione

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

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top