我對編程相當陌生,因此非常感謝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