我无法打印最后一个逗号:
public void displayArrayMethod(int array[][])
{
for(int row=0; row<array.length; row++)
{
for(int column=0; column<array[row].length; column++)
{
System.out.print(array[row][column]+",");
}
}
}
输出:
1,2,3,4,5,6,7,8,9,
答案 0 :(得分:3)
不是寻找摆脱最后一个逗号的方法,而是首先避免使用它。一种方法是让Java的流程繁重,而不是你自己编写循环:
public void displayArrayMethod(int array[][]) {
System.out.print(Arrays.stream(array)
.flatMapToInt(Arrays::stream)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",")));
}
答案 1 :(得分:1)
此循环在附加逗号之前检查最后一列。
编辑:添加了完整的实施,以帮助查找可能导致评论中出现问题的用户可能存在的差异。此代码返回1,2,3,4,5,6,7,8,9
public class Sandbox { //opens class
public static void main(String[] args) {
int[][] array = {
{1, 2, 3, 4, 5, 6, 7, 8, 9}
};
displayArrayMethod(array);
System.out.println("wait");
}
public static void displayArrayMethod(int array[][]) {
for(int row=0; row<array.length; row++)
{
if(row == array[row].length - 1 && column == array[row].length - 1)
{
if(column == array[row].length - 1)
{
System.out.print(array[row][column]);
}
else
{
System.out.print(array[row][column]+",");
}
}
}
}
}
答案 2 :(得分:1)
你可以通过多种方式实现这一目标......
opt1:result.substring(0,result.length() - 1)
opt2:Arrays.deepToString(x)并不是你所需要的,但几乎相同
opt3:stringBuilder(john skeet way ...)
public static void main(final String[] args) {
final int[][] x = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
displayArrayMethod(x);
System.out.println(Arrays.deepToString(x));
displayArrayMethod2(x);
}
private static void displayArrayMethod2(final int[][] x) {
final StringBuilder sb = new StringBuilder();
String prefix = "";
for (final int[] element : x) {
for (final int element2 : element) {
sb.append(prefix);
prefix = ",";
sb.append(element2);
}
}
System.out.println(sb.toString());
}
public static void displayArrayMethod(final int array[][]) {
String result = "";
for (final int[] element : array) {
for (final int element2 : element) {
result += element2 + ",";
}
}
System.out.println(result.substring(0, result.length() - 1));
}
答案 3 :(得分:0)
for(int column=0; column<array[row].length-1; column++){
System.out.print(array[row][column]+",");
}
System.out.print(array[row][array[row].length-1];