【发布时间】:2011-12-24 02:54:24
【问题描述】:
我对编程还很陌生,所以很欣赏外行的谈话。
我的任务是读取一个文件的内容,该文件将包含 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
我目前正在正确打印数组。
将每个索引值乘以常数(用户输入)的最佳方法是什么?
【问题讨论】:
-
我看到的第一个问题是你没有为矩阵分配任何东西。您实际上是在 readFile 方法中创建一个名为 matrix 的新二维数组。第二个问题是,在 readFile 方法中,你有 matrix[0][0] = numbers;在一个循环中......所以你只将值分配给矩阵的第一个位置。
-
“它接受第一行,但之后失败。”失败怎么办?请明确点。顺便说一句 - 你有问题吗?
-
aleph_null - 您对如何将每个“双”存储到索引中以使“双”=(x,y)索引有什么建议吗?另外,在提交之前的索引后如何进入下一个索引?
-
Andrew Thompson - 我收到的错误如下 - “线程“主”java.lang.NumberFormatException 中的异常:对于输入字符串:sun.misc.FloatingDecimal.readJavaFormatString 处的“1.00 -2.00 3.00” (FloatingDecimal.java:1241) 在 java.lang.Double.parseDouble(Double.java:540) 在 CS240Lab8a.readFile(CS240Lab8a.java:63) 在 CS240Lab8a.main(CS240Lab8a.java:32) Java 结果:1" -我的问题在底部 (1,2,3) - 如何完成这些任务