简体   繁体   English

给定行号Java,将2D数组的行作为逗号分隔的字符串返回

[英]Return row of 2D array as comma delimited string given row number Java

I'm attempting to create a function that will accept the row number of a multi-dimensional array as an integer and return a string that contains a comma-delimited list of the values in that row. 我正在尝试创建一个函数,该函数将多维数组的行号接受为整数,并返回一个字符串,该字符串包含该行中值的逗号分隔列表。 this.desks is the 2d array containing string values. this.desks是包含字符串值的二维数组。 this.oneRow is a string that I would like the function to return. this.oneRow是我希望函数返回的字符串。 sb is a stringbuilder. sb是一个stringbuilder。 Row is the value of the row that should be returned. Row是应返回的行的值。 This block of code is what I've managed to find but it returns the entire array. 这是我设法找到的代码块,但它返回了整个数组。 I've attempted to look at the syntax for string builder and modify it to no avail. 我试图查看字符串生成器的语法并将其修改为无济于事。 Would someone mind assisting? 有人介意协助吗?

public String getRow(int row) {

    for(String[] s1 : this.desks) {
        this.sb.append(Arrays.toString(s1));
        this.oneRow = sb.toString();
       }
     return this.oneRow;
this.oneRow += sb.toString();

要连接的值。

You shouldn't be looping if you want the first row, use index row (after first checking it's a valid index). 如果要第一行,则不应该循环,使用索引row (在首先检查它是否为有效索引之后)。 Like, 喜欢,

public String getRow(int row) {
    if (row < desks.length) {
        return Arrays.toString(desks[row]);
    }
    return ""; // <-- or null, or throw an exception.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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