gpt4 book ai didi

java - 将数据导入二维公共(public)数组

转载 作者:行者123 更新时间:2023-12-01 14:38:39 24 4
gpt4 key购买 nike

我正在为学校开发一个程序,它将 3 个程序组合在一起(一个转置二维数组,一个将对角线相加并告诉它们,一个将行相加)。我遇到的问题是将所有数据导入二维数组“输入”,以便所有方法都可以使用它。每次我尝试运行该程序时,它都会给出“java.lang.NullPointerException:null”。我该如何解决这个问题?

我的代码:

    import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* This is program combines 3 programs in 1
*
* @author (your name)
* @version (a version number or a date)
*/
public class threeprogs
{
// instance variables - replace the example below with your own
private int x;
public static int[][] input;
public static int[][] output;
/**
* Runs All methods
*/
public static void main(String[] args)
{
//inputs info
File file = new File("prog464a.dat");
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextInt())
{
for(int i = 0; i<5; i++)
{
for(int j = 0; j<5; j++)
{
input[i][j] = scanner.nextInt();
output[i][j] = input[i][j];
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int programs = 0;
while(programs <3)
{
//make all programs execute here
switch (programs)
{
case 0: transpose();
break;
case 1: AddDiag();
break;
case 2: AddRowsandCol();
break;
}
//prints output
for(int i=0; i<5;i++)
{
System.out.print("\n");
for(int j=0;j<5;j++)
{
System.out.print(output[i][j]);
}
}
}
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public static int[][] transpose()
{
for(int i=0; i<input.length; i++)
{
for(int j=1; j<input[0].length; j++)
{
output[i][j] = input[j][i];
}
}
return output;
}
public static String AddRowsandCol()
{
int total = 0;
int loop = 0;
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
if(loop<i)
{
output[loop][5] = total;
total = 0;
}
total += output[i][j];
}
}
return "Origional Matrix\n" +input +"\n\nWithTotals" +output;
}
public static String AddDiag()
{
int totala = 0;
int totalb = 0;
int count = 5;
for(int i=0; i<5; i++)
{
count--;
totala += input[i][i];
totalb += input[i][count];
}
return "Main Diagonal Sum " +totala +"\nOther Diagonal Sum" +totalb;
}
}

最佳答案

在分配任何值之前应初始化input数组

int[][] input = new int[5][5];

同样对于输出数组:

int[][] output = new int[5][5];

关于java - 将数据导入二维公共(public)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16222019/

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