简体   繁体   中英

How do I print a 2d array?

My array is:

String[][] name = new String[15][2];
int rowNumber = 0;

My add button is:

name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();

I do not know what to put in my list button (lists the first name and last name) into my TextArea called outPut .

The Whole Code:

`
public class StudentGradesView extends FrameView {
 String[][] name = new String[15][2];
 double[][] testMark = new double[15][4];
 int rowNumber = 0;


    private void btnAddMouseClicked(java.awt.event.MouseEvent evt) {                                    
        name[rowNumber][0] = firstName.getText();
        name[rowNumber][1] = lastName.getText();
        rowNumber ++;
    }                                   

    private void btnListMouseClicked(java.awt.event.MouseEvent evt) {                                     
      String outputStr = "";
for(int i=0; i < rowNumber; i++) {
    outputStr += name[rowNumber][0] + " " + name[rowNumber][1] + "\n";
}outPut.setText(outputStr);
    }                                                                               

}`
String st = "";
for (int i = 0; i < 15; i++)
    st += name[i][0] + " " + name[i][1] + "\n";
outPut.setText(value);

This loops over the array and creates a string containing all the full names, separated by a line break.

This then sets the text using outPut.setText(value);

Okay, I think I get what you want now.

First we take the inputs...

name[numberOfInputs][0] = firstName.getText();
name[numberOfInputs][1] = lastName.getText();
numberOfInputs += 1;

Now you want to output this to a textarea...

String outputStr = "";
for(int i=0; i < numberOfInputs; i++) {      
    outputStr += name[i][0] + " " + name[i][1] + "\n"; 
}

Then set your output textarea

outPut.setText(outputStr);

You are getting nulls because you are specifying a static array size but you (probably) are not filling up the array with test cases up to that amount. So you are printing elements of the array that are simply not populated.

Edit: for comments.

for(String[] s1d : s2d)
   for(String s : s1d)
     System.out.println(s);

A simple way using for() construct

将任何数组打印到任何深度的最简单方法是使用Arrays.deepToString()

System.out.println(Arrays.deepToString(array));

try this:

import java.util.Arrays;
.
.
.


String[][] a = { { "john" },
                    { "jones" }
                  };
   System.out.println(Arrays.deepToString(a)); //whole string array

   System.out.println(Arrays.deepToString(a[0])); //john
   System.out.println(Arrays.deepToString(a[1])); //jones

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