我正在尝试运行一个Java程序来显示9个输入框,请求姓名和考试分数,并在消息框中显示每个分数的名称和适当等级。我尝试过这样的事情:
import javax.swing.JOptionPane;
public class StudentGrade {
public static void main(String[] args) {
String inputname;
String inputscore;
int number;
inputcourse = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputcourse) + " " + "D"); }
else if (number <50){
System.out.println((inputcourse) + " " + "C");}
else if (number <60){
System.out.println((inputcourse) + " " + "B");}
else System.out.println((inputcourse) + " " + "A");}
}
但是,这只能运行一次。请问,如何让它运行九次?感谢。
答案 0 :(得分:3)
要在控制结构中循环,您可以使用for,while循环或do-while循环。对于for循环,你应该尝试:
public class StudentGrade{
public static void main(String[] args){
for (int i=0; i<9; i++){ repeat 9 times
// all the code you have in your main method now
}
}
}
对于while循环,您应该尝试:
public class StudentGrade{
public static void main(String[] args){
int i=0;
while (i++ < 9){ //repeat 9 times
// all the code you have in your main method now
}
}
}
对于do-while循环,您应该尝试:
public class StudentGrade{
public static void main(String[] args){
int i=1;
do{ //repeat 9 times
// all the code you have in your main method now
}while (i++ < 9);
}
}
希望这有帮助。
答案 1 :(得分:3)
试试这个它会起作用。在您的代码中选中输入名称和输入课程 或将inputCourse更改为inputName
import javax.swing.JOptionPane;
public class world {
public static void main(String[] args) {
String inputname;
String inputscore;
int number;
for(int i=0;i<9;i++){
inputname = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputname) + " " + "D");
}else if (number <50){
System.out.println((inputname) + " " + "C");
}else if (number <60){
System.out.println((inputname) + " " + "B");
}else {
System.out.println((inputname) + " " + "A");
}
}
}
}
答案 2 :(得分:1)
将代码放在for循环中:
for(int i=0; i<9; i++){
inputcourse = JOptionPane.showInputDialog("Enter name");
inputscore = JOptionPane.showInputDialog("Enter score");
number = Integer.parseInt(inputscore);
if (number < 40){
System.out.println ((inputcourse) + " " + "D");
} else if (number <50){
System.out.println((inputcourse) + " " + "C");
} else if (number <60){
System.out.println((inputcourse) + " " + "B");
} else {
System.out.println((inputcourse) + " " + "A");
}
}