gpt4 book ai didi

java - 将文件内容读入二维数组

转载 作者:行者123 更新时间:2023-12-02 08:06:45 24 4
gpt4 key购买 nike

我对编程相当陌生,所以很感谢外行人的演讲。

我的任务是读取一个文件的内容,该文件将包含 9 个值(3x3 数组),然后将内容放入相应的索引中。

例如,

二维数组的内容是...

1.00   -2.00   3.00   
4.00 1.00 -1.00
1.00 2.00 1.00

内容读入后,需要打印。然后程序将提示用户输入标量乘数,例如“4”。然后程序应该使用新输出打印新数组。

我目前有这个,

import java.io.*;
import java.util.*;


public class CS240Lab8a {

/**
* @param args the command line arguments
*/
static double [][] matrix = new double[3][3];
static Scanner input = new Scanner(System.in);


public static void main(String[] args) throws IOException
{
// Variables
String fileName = "ArrayValues.txt";




// print description
printDescription();

// read the file
readFile(fileName);

// print the matrix
printArray(fileName, matrix);

// multiply the matrix
multiplyArray(fileName, matrix);


}


// Program Description
public static void printDescription()
{
System.out.println("Your program is to read data from a file named ArrayValues.txt and store the values in a 2D 3 X 3 array. "
+ "\nNext your program is to ask the user for a scalar multiplier \n"
+ "which is then used to multiply each element of the 2D 3 X 3 array.\n\n");
}



// Read File
public static void readFile(String fileName) throws IOException
{
String line = "";

FileInputStream inputStream = new FileInputStream(fileName);
Scanner scanner = new Scanner(inputStream);
DataInputStream in = new DataInputStream(inputStream);
BufferedReader bf = new BufferedReader(new InputStreamReader(in));

int lineCount = 0;
String[] numbers;
while ((line = bf.readLine()) != null)
{
numbers = line.split(" ");
for (int i = 0; i < 3; i++)
{
matrix[lineCount][i] = Double.parseDouble(numbers[i]);
}

lineCount++;
}
bf.close();

}


// Print Array
public static void printArray(String fileName, double [][] array)
{
System.out.println("The matrix is:");

for (int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println();
}

public static double multiplyArray(String fileName, double[][] matrix)
{
double multiply = 0;

System.out.println("Please enter the scalar multiplier to be used.");
multiply = input.nextDouble();

for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
matrix[i][j]

return multiply;
}



} // end of class

我目前可以正确打印数组。

将每个索引值乘以常数(用户输入)的最佳方法是什么?

最佳答案

您在这里缺少一个额外的步骤。

读完该行后,您必须拆分该行并在各个数字上解析Double。

int lineCount = 0;
while ((line = bf.readLine()) != null)
{
String[] numbers = line.split(" ");
for ( int i = 0 ; i < 3 ; i++)
matrix[lineCount][i] = Double.parseDouble(numbers[i]);

lineCount++;
}

此外,您的 readFile 不需要返回任何内容。只需将矩阵变量设置为全局即可。

关于java - 将文件内容读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8045266/

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