我正在尝试创建一个代码,要求用户输入3个单独的测试分数。 我正在使用JOptionPane进行对话框和输入。 在询问我的第一个值之后,应该打开另一个并询问我的第二个值,依此类推。 它没有这样做,而是关闭了,并且没有为我提供第二个对话框。
这是我的代码。
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GradeTest
{
public static void main(String[] args)
{
int Value1;
int Value2;
int Value3;
int average;
Scanner keyboard = new Scanner(System.in);
JOptionPane.showInputDialog("What is your first value?");
Value1 = keyboard.nextInt();
JOptionPane.showInputDialog("What is your second value?");
Value2 = keyboard.nextInt();
JOptionPane.showInputDialog("What is your second value?");
Value3 = keyboard.nextInt();
average = Value1 + Value2 + Value3;
average = average / 3;
JOptionPane.showMessageDialog(null, "The average grade is "
+ average + "%.");
if(average < 60)
{
JOptionPane.showMessageDialog(null, "The grade for "
+ average + "% is an F.");
}
else
{
if(average < 70)
{
JOptionPane.showMessageDialog(null, "The grade for "
+ average + "% is a D.");
}
else
{
if(average <80)
{
JOptionPane.showMessageDialog(null, "The grade for "
+ average + "% is a C.");
}
else
{
if(average <90)
{
JOptionPane.showMessageDialog(null, "The grade for "
+ average + "% is a B.");
}
else
{
if(average <100)
{
JOptionPane.showMessageDialog(null, "The grade for "
+ average + "% is an A.");
}
}
}
}
}
}
}
答案 0 :(得分:0)
JOptionPane.showInputDialog
返回用户输入的字符串。使用Integer.parseInt
方法将返回值转换为整数。您不应使用keyboard.nextInt()
来等待来自控制台的用户输入。
答案 1 :(得分:0)
默认的System.in Scanner是命令行输入阅读器。如果将值设置为等于控制台输入,那么使用JOptionPane输入绝对不执行任何操作。通常,您不应将控制台程序与GUI混合使用。通过使用JOptionPane结果,您可能想要做的事情更像这样。
...
int Value1, Value2, Value3, average;
Value1 = Integer.parseInt(JOptionPane.showInputDialog("What is your first value?"));
Value2 = Integer.parseInt(JOptionPane.showInputDialog("What is your second value?"));
Value3 = Integer.parseInt(JOptionPane.showInputDialog("What is your third value?"));
average = (Value1 + Value2 + Value3) / 3;
JOptionPane.showMessageDialog(null, "The average grade is " + average + "%.");
...
虽然这不是您的问题,但是您的if else子句非常长,您应该将它们缩短到这个长度。
String avgGrade = "";
if (average < 60)
avgGrade = "F";
else if (average < 70)
avgGrade = "D";
else if (average < 80)
avgGrade = "C";
else if (average < 90)
avgGrade = "B";
else
avgGrade = "A";
JOptionPane.showMessageDialog(null, "The grade for "+ average + "% is "+avgGrade+".");