我的 switch-case 选项和 joptionpane 遇到问题。选择四个选项之一后,程序结束。它不显示选择。它应该显示选择/选择。
import javax.swing.JOptionPane; // JOptionPane call
public class OnlineStore
{
// public static void main(String[] args) // main program
public void display_menu() // Not the main program but the main menu.
{
String main_selection;
int mSelect;
main_selection = JOptionPane.showInputDialog("Welcome!\n\n1. Add T- Shirt Order\n2. Edit T-Shirt Order\n3. View Current Order\n4. Checkout\n\nPlease enter your choice: ");
mSelect = Integer.parseInt(main_selection);
}
public OnlineStore() // Switch-case program
{
display_menu(); // Call display menu.
switch (mSelect)
{
case 1:
JOptionPane.showMessageDialog(null, "Option 1");
break;
case 2:
JOptionPane.showMessageDialog(null, "Option 2");
break;
case 3:
JOptionPane.showMessageDialog(null, "Option 3");
break;
case 4: // Deliberately not including a default selection.
JOptionPane.showMessageDialog(null, "Option 4");
break;
}
}
public static void main(String[] args) // main program
{
new OnlineStore(); // Call out the program.
}
}
当我使用扫描仪时,结果正常。
最佳答案
在类内而不是在方法内声明 mSelect 变量。
public class OnlineStore {
int mSelect;
// public static void main(String[] args) // main program
public void display_menu() // Not the main program but the main menu.
{
String main_selection;
main_selection = JOptionPane.showInputDialog("Welcome!\n\n1. Add T- Shirt Order\n2. Edit T-Shirt Order\n3. View Current Order\n4. Checkout\n\nPlease enter your choice: ");
mSelect = Integer.parseInt(main_selection);
}
public OnlineStore() // Switch-case program
{
display_menu(); // Call display menu.
switch (mSelect) {
case 1:
JOptionPane.showMessageDialog(null, "Option 1");
break;
case 2:
JOptionPane.showMessageDialog(null, "Option 2");
break;
case 3:
JOptionPane.showMessageDialog(null, "Option 3");
break;
case 4: // Deliberately not including a default selection.
JOptionPane.showMessageDialog(null, "Option 4");
break;
}
}
public static void main(String[] args) // main program
{
new OnlineStore(); // Call out the program.
}}
关于java - Joptionpane 不处理 switch-case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31980282/