来自用户的文件输入

时间:2011-02-16 05:21:06

标签: java file file-io

我试图从用户那里获取文件名的输入,然后继续进行所有计算。但它一直给我一个错误。该文件存在于同一目录中。

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

public class test{
public static void main(String args[]) throws FileNotFoundException {
//File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(System.in);
scanner.nextLine(); // removes the first line in the input file 
String rowLine = scanner.nextLine();
String[] arr = rowLine.split("=");
int rows = Integer.parseInt(arr[1].trim());

String colLine = scanner.nextLine();
String[] arr2 = colLine.split("=");
int cols = Integer.parseInt(arr2[1].trim());
double [][]matrix = new double [rows][cols];

 for (int i=0; i<rows;i++){
     for (int j=0; j<cols;j++) {
         matrix[i][j]= scanner.nextDouble();
        } 
}


System.out.println(rows);
System.out.println(cols);  

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

}     }

2 个答案:

答案 0 :(得分:0)

您意识到您只使用System.in类型的扫描仪,对吧?这意味着您甚至没有查看文件,而只是查看用户输入。这与您是否注释掉第一行无关。要使用文件,您可以使用FileInputStream或其他几个文件处理类。


FileInputStream fs = new FileInputStream(new File("matrix1.txt"));
//do stuff with the stream

继承了FileInputStream的java文档:http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileInputStream.html

编辑:在看到你对实际错误的评论之后,我意识到代码的问题多于你处理输入的方式。您的错误几乎肯定发生在前两个数组访问器之一,即1。trim()调用。这意味着用户输入在“=”符号的右侧没有任何内容,或者用户输入中没有“=”符号。

答案 1 :(得分:0)

代码存在一个问题。扫描程序只会从命令行为您提供文件名。因此,您需要先获取命令行参数,然后使用带有文件对象的构造函数再创建一个扫描程序。 e.g。

            Scanner scanner = new Scanner(System.in);
    Scanner fileScanner = new Scanner(new File(scanner.nextLine()));
    String rowLine = fileScanner.nextLine();
    System.out.println(rowLine);
    String[] arr = rowLine.split("=");
    int rows = Integer.parseInt(arr[1].trim())