gpt4 book ai didi

java - 如何打印空的二维数组而不出现空指针异常

转载 作者:行者123 更新时间:2023-12-02 04:05:01 25 4
gpt4 key购买 nike

我对 Java 比较陌生,对于一个学校项目,我需要打印一个 2D 数组。该项目的基础是使用值 null 打印它。但我无法将其放入 for 循环而不得到 java.lang.NullPointerException。有人可以帮忙吗?

private int ROWS;
private int COLUMNS;
private int WIDTH;

private String[][] sheet;
private String[][] values;
private int precision;

public SpreadSheet(int rows, int cols, int width, int precision) {
this.ROWS = rows;
this.COLUMNS = cols;
/*this.WIDTH = width;
this.precision = precision;*/
}

public void printSheet(){
for (int i = 0; i < sheet.length; i++) {
for (int j = 0; j < sheet[i].length; j++) {
System.out.println(sheet);
}
System.out.println("\n");
}
}

主要:

import java.util.Scanner;
public class DemoSpreadSheet {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
SpreadSheet sh = new SpreadSheet(4, 6, 15, 2);
sh.printSheet();
}

}

最佳答案

对 SpreadSheet 函数进行一些小更改:

public SpreadSheet(int rows;int cols;int width;int precision)
{
this.Sheet=new String[rows][cols];
/*creates an array with 4 rows and 6 columns..(assuming this is what you wanted to do)*/
}

您的打印表函数也存在错误:

System.out.println(Sheet); //illogical
/*sheet does not print the content of the array Sheet*/

将其更改为:

System.out.println(Sheet[i][j]);
/*this will print null */

关于java - 如何打印空的二维数组而不出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34397660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com