0

我的代码没有从文件中读取该行。但我不确定为什么。初级Java,任何输入都是有帮助的。

谢谢。

public class ReverseWords {

public static void main(String [] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Enter File Name: ");
    String fileName = in.nextLine();
    File f = new File(fileName);
    try {
        Scanner input = new Scanner(f);
                    int n = input.nextInt();  
        String line = input.nextLine();
            System.out.println(line);
            String [] words = line.split(" ");

            for(int i=0; i<words.length; i++){
                System.out.println(words[i]);

            }


             } catch (FileNotFoundException e) {
        e.printStackTrace();
     }

}    
4

2 回答 2

1

由于没有文件内容,我只能猜测。

nextInt()不会更改 中的行计数器Scanner,因此nextLine()call 将返回您当前所在行的其余部分。这可能不是您想要的,这就是没有读取任何行的原因。

为避免这种情况,您可以通过在您之后进行额外nextLine()调用来显式更改行计数器nextInt()

int n = input.nextInt(); 
input.nextLine();
String line = input.nextLine();

来自Scanner.nextLine API 文档:

此方法返回当前行的其余部分,不包括末尾的任何行分隔符。

于 2013-05-31T17:22:33.310 回答
0

我假设你有 filenotfound 异常。

您必须指定绝对路径作为输入。

drive:/sample/input.txt

首先尝试从直接读取源文件

 Scanner sc = new Scanner(new File("drive:/dir/file"));

或者您可以将文件放置在您的项目所在的位置。[文件夹被命名为项目名称] 在这种情况下,您可以简单地指定“file.extesion”作为从该文件读取的输入。

但是如果文件存在:(可以用 new File(filename.ext).exists() 检查)然后检查是否有输入要读取

要读取整个文件或更多行,您应该将其放入循环中(实际上您只读取了一行)

while(sc.hasnextLine())
{
 line=sc.nextLine()    //check it first and then process
 //process this line for words 

}

于 2013-05-31T17:27:55.127 回答