我正在编写一个类似于物理课程的java程序:
import javax.swing.JOptionPane;
public class PhysicsClass {
public static void main(String[] args) {
int g = -1;
while (g<0){
String input = JOptionPane.showInputDialog("Welcome! What's your name? ");
if(input.length() > 0){
g++;
System.out.println("Great! Lets begin.");
}
else{
System.out.println(" ok then.");
System.exit(0);
}
}
String[] firstChoice = {"Kinematics", "Dynamics", "Impulse/Momentum", "Energy/Power"};
JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
int i = 0;
while (i<0){
String Choice = "";
if (Choice == firstChoice[0]){
Kinematics.IntroToKinematics();
i++;
}
else if (Choice == firstChoice[1]){
Dynamics.DynamicsIntro();
i++;
}
else if (Choice == firstChoice[2]){
ImpulseAndMomentum.ImpulseAndMomentumIntro();
i++;
}
else if (Choice == firstChoice[3]){
EnergyAndPower.EnergyAndPowerIntro();
i++;
}
else{
System.out.println("Please pick one.");
}
}
我想要你在第一个选择数组中选择的任何选择然后转到受尊敬的类。因此,如果我选择运动学,它将调用运动学类,前几行是:
import javax.swing.JOptionPane;
public class Kinematics {
public static void IntroToKinematics() {
JOptionPane.showInternalMessageDialog(null, "Kinematics is one of the most basic"
+ " ideas of Newtonian Physics. It encompasses: speed, distance, time"
+ " displacement, acceleration and many key base concepts that form the the "
+ " foundation for most physic subjects. It will poke its head in everything"
+ "we cover.", "intro", JOptionPane.INFORMATION_MESSAGE);
}
}
它没有给我任何错误但是当我从数组中选择其中一个字符串时,它什么也没做。我认为它可能与我使用的if else语句有关。感谢任何和所有帮助,我仍然相对较新的Java所以任何提示将不胜感激。
答案 0 :(得分:4)
使用等于来比较字符串,如 -
if(Choice.equals(firstChoice[0])){...}
答案 1 :(得分:1)
首先,您要将输入框的结果存储在某处:
String choice = JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
然后使用.equals
进行字符串比较而不是==
if (choice.equals(firstChoice[0])){
Kinematics.IntroToKinematics();
}
不需要循环。
答案 2 :(得分:0)
您没有将选择值绑定到选定值,它总是将其与“”
进行比较答案 3 :(得分:0)
首先在showInputDialog中你应该做这样的事情
String Choice = "";
Choice= (String) JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
首先声明变量Choice,然后将inputDialog值设置为选择,此时你的while应该是这样的
int i = 0;
while (i<=0){
//do something
}
因为它第一次运行i<0
,因为0不低于0(因为你声明int i =0;
)不会运行。
你可以继续使用""
,但这样的事情应该更有效率
if (Choice.equals(firstChoice[0])){
Kinematics.IntroToKinematics();
i++;
}
最后尝试在变量中首先使用小写,例如:tableSize