我对编程相当陌生,因此非常感谢layman的演讲。将文件内容读入2D阵列
我的任务是读取一个文件的内容,它将包含9个值(3x3数组),然后将内容放入相应的索引中。
例如,
2D阵列的内容是...
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
我现在有它打印阵列正常。
用常数(用户输入)乘以每个索引值的最佳方式是什么?
我看到的第一个问题是你没有给矩阵分配任何东西。你实际上是在readFile方法中创建一个名为matrix的NEW 2d数组。第二个问题是,在readFile方法中,你有矩阵[0] [0] =数字;在一个循环中...所以你只将值赋给矩阵的第一个位置。 –
*“它接受第一行,但之后失败。”*失败如何?请明确点。顺便说一句 - 你有问题吗? –
aleph_null - 你有建议如何将每个'double'存储到索引中,使'double'=(x,y)索引?另外,如何在事先提交之后进入下一个索引? – fisherml