If statement if语句正在执行,else if语句不在java中
//菜单方法从这里开始If statement if语句正在执行,else if语句不在java中,if-statement,drop-down-menu,If Statement,Drop Down Menu,//菜单方法从这里开始 import javax.swing.JOptionPane; public class sam{ public static void main(String[]args){ String a; String b; int c; sam s1 = new sam(); a=s1.getInfo(); c=s1.getBalance(); b=s1.getMenu(a,c);
import javax.swing.JOptionPane;
public class sam{
public static void main(String[]args){
String a;
String b;
int c;
sam s1 = new sam();
a=s1.getInfo();
c=s1.getBalance();
b=s1.getMenu(a,c);
}
//if语句正在正确执行
public String getMenu (String c, Integer d) {
String[] a;
String[] choices = { "Account Balance", "Deposit", "Withdraw", "User Account", "Exit options"};
String input = (String) JOptionPane.showInputDialog(null, "What would you like to do?",
"ATM menu", JOptionPane.QUESTION_MESSAGE, null,choices,choices[0]);
if ((choices[0] == choices[0])){
JOptionPane.showMessageDialog(null,"Your Account Balance is: "+d,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//但当我选择account balance时,它会显示if语句,而不是else if语句
else if ((choices[1] == choices[1])){
String in=JOptionPane.showInputDialog("Deposit: ");
int deposit=Integer.parseInt(in);
int add=d+deposit;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+add,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
//我对编程很陌生,我匆忙地将其编码为期末考试。您所有的
if
语句都将评估为true
。我认为您的意图是将字符串c
与选项
数组中的每个字符串
进行比较
比较字符串时
始终使用.equals()
而不是=
例如:
else if ((choices[2] == choices[2])){
String in=JOptionPane.showInputDialog("Withdraw: ");
int withdraw=Integer.parseInt(in);
int sub=d+withdraw;
JOptionPane.showMessageDialog(null,"Your Current Balance: "+sub,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[3] == choices[3])){
JOptionPane.showMessageDialog(null," "+c,"ATM machine",JOptionPane.INFORMATION_MESSAGE);}
else if ((choices[4] == choices[4])){
JOptionPane.showMessageDialog(null,"The program will be terminated in a few seconds","ATM machine",JOptionPane.INFORMATION_MESSAGE);
}
return input;
}
我认为你没有抓住
if
和else if
条款的要点。。。实际上,所有条件的计算结果都将为true(如果1==1,则它们与相同),但当代码在第一个if
中传递时,它只会传递下一个else if
语句。你不能同时执行if
和else if
指令。谢谢它帮助我认识到这一点:)谢谢它帮了我很多。我仍然对如何使用if语句感到困惑,这就是为什么我通常不在项目中使用它们来编写代码的原因。如果语句是编程中最重要的概念之一,那么花一些时间来了解它们是值得的:)。如果这回答了您的问题,请不要忘记将其标记为已接受的答案。我将再次感谢:)
if (c.equals(choices[0])) {
// code
} else if (c.equals(choices[1])) {
//code
} else if (c.equals(choices[2])) {
// code
}