【发布时间】:2014-01-28 07:06:20
【问题描述】:
谁能帮助我处理 if 和 else 语句?每当我输入某些内容时,它只会说“退出再见”,这只会在我输入 -0 时发生。我的老师这周不在,所以我没有人可以寻求帮助。
package game;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Random;
import javax.swing.JOptionPane;
public class GameFrame {
/**
* @param args
*/
public static void main(String[] args) {
// num1 - Variable to store the first value
// num2 - Variable to store the second value
// answer - Variable to accept user input
int num1, num2, answer=0;
/*@reader - The reader which accepts user input*/
BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));
/*@quit - Variable used to exit the program*/
boolean quit = false;
/*@generator - The Random number generator*/
Random generator = new Random();
while (quit == false)
{
//Generate First Random Number between 1-100
num1 = generator.nextInt(100);
//Generate First Random Number between 1-100
num2 = generator.nextInt(100);
//Displays the math equation
String input = JOptionPane.showInputDialog(null,num1+ "+" + num2 + " = ");
//Accepts the user's input and converts it to int value
int number = Integer.parseInt(input);
//Lets assume if user enters -99, it means they want to exit the program
if (answer == -0)
{
JOptionPane.showMessageDialog(null, "Exit Program: Good Bye!\n");
quit = true;
}else if (answer == (num1+num2))
JOptionPane.showMessageDialog(null,"Correct Answer!\n");
else{
JOptionPane.showMessageDialog(null,"Incorrect Answer\n");
}
}
}
}
【问题讨论】:
-
如果您以前从未制作过 GUI 程序,那么尝试将控制台程序转换为 GUI 程序并不是一件容易的事。您需要了解事件驱动编程。我建议你看看Swing tutorials
-
要记住的一点是,当您编辑问题(帖子)时,不要覆盖原始问题,因为这可能会使编辑之前回答的答案无效。相反,在原始帖子下方,只需写 EDIT 并将编辑后的内容附加到帖子中。
标签: java swing jframe jlabel joptionpane