简体   繁体   中英

How do I add an integer to an integer ArrayList in a GUI?

I am trying to add the Integer inputted by the user to the ArrayList . It's originally a String , so I converted it to an Integer . I added the Integer to the Arraylist , but now I'm not sure how to display it. I want to be able to keep adding marks, and have all the marks displayed on the screen. I tried a for loop, but I'm not sure what the second parameter would be.

Edit: for (i=0; ... ; i++) -- What would go in the second place?

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {  
    String strInputMark;
    int intInputMark;

    strInputMark = txtInputMark.getText();
    intInputMark = Integer.parseInt(strInputMark);

    ArrayList<Integer> Marks = new ArrayList<>();

    int intMarks;
    Marks.add(intInputMark);
}

You can try this

String strInputMark;
Integer intInputMark;

strInputMark = txtInputMark.getText();
intInputMark = Integer.valueOf(strInputMark);

ArrayList<Integer> Marks = new ArrayList <>();

int intMarks;
Marks.add(intInputMark);

The short answer is i < Marks.size()

for (int i = 0; i < Marks.size(); i++) {
   System.out.println(Marks.get(i));
}

Try this for loop:

String output = "";

    for(int i = 0; i < Marks.size(); i++){
        output += "\n"+Marks.get(i);
    }

    JOptionPane.showMessageDialog(null, output);

I think the answer is two-fold. First, you need to move 'Marks' outside of the method scope so it can be accessible and continually appended two as input continues. Second, as @Umesh said, Marks.size() will give you the total number of elements in your arraylist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM