if条件与JOptionPane一起使用showMessageDialog

时间:2013-11-08 20:07:55

标签: if-statement conditional-statements joptionpane

运行时下面的代码只生成标记为< 30的最后一个学生的姓名我希望学生的所有姓名都显示在同一个消息对话框中。请帮忙。谢谢,我对编码很新。

import javax.swing.JOptionPane;
class marks
{
    public static void main(String args[])
    {
    String name=" ";
    int marks=0;

    for(int x=0; x<3; x++) 
        {
        name=JOptionPane.showInputDialog(null,"Please enter the name");
        marks=Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter the marks"));
        }

    if (marks<30)
            {
        (JOptionPane.showMessageDialog(null,"the students who got marks below 30 are: "+name));
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我认为你需要阅读一些basics。同样为此目的使用数组而不是一个变量。我改变了你的代码,我认为它可以做你想要的:

public class marks {

    public static void main(String args[]) {
        int count = 3;
        String[] name = new String[3];
        int[] marks = new int[3];
        for (int x = 0; x < count; x++) {
            name[x] = JOptionPane.showInputDialog(null, "Please enter the name");
            marks[x] = Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter the marks"));
        }
        String names="";
        for(int i = 0;i<count;i++){
            if (marks[i] < 30){
                names+= name[i]+", ";
            }
        }
        if(names.endsWith(", ")){
            names = names.substring(0,names.length()-2);
        }
        if(!names.isEmpty()){
            JOptionPane.showMessageDialog(null,"the students who got marks below 30 are: " + names);
        }
    }
}

答案 1 :(得分:0)

import java.util.ArrayList;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
class marks
{

    public static void main(String args[])
    {int x=0;
//    String name=" ";
//    int marks=0;
    ArrayList<Integer> marks= new ArrayList<Integer>();
     ArrayList<String> name= new ArrayList<String>();
    ArrayList<String> array = new ArrayList<String>();
    for(x=0; x<3; x++)
        {
        name.add(JOptionPane.showInputDialog(null,"Please enter the name"));
        marks.add(Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter the marks")));

    }

   // if (marks<30)
    for(x=0 ; x<name.size(); x++)
            {

             if(marks.get(x)<30){
           array.add(name.toString());
//         JOptionPane.showMessageDialog(null,"the students who got marks below 30 are: "+name.);
           break;
        }

    }
     JOptionPane.showMessageDialog(null, new JScrollPane(new JList(array.toArray())));
}
}