我正在尝试制作一个简单的银行帐户程序来学习课程和OOP。你可能猜到,我是Java的新手。
无论如何,我的switch语句不起作用。我正在尝试根据输入的字符串制作每个案例。
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);
}
答案 0 :(得分:3)
在每个案例结束时,您错过了 break 语句。
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;
如果没有break语句,所有这些语句都将被执行
答案 1 :(得分:1)
如果您使用Strings
或更高版本,则可以在switch
语句中使用Java 7
,否则您无法
答案 2 :(得分:1)
您缺少break;
语句,因此将执行所选case
之后的所有语句。
以下是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
答案 3 :(得分:1)