gpt4 book ai didi

java - 在java中通过命令行输入一个文本文件

转载 作者:行者123 更新时间:2023-11-30 08:31:05 27 4
gpt4 key购买 nike

我正在尝试编写一个程序,通过命令行输入一个文本文件,然后打印出文本文件中的字数。我已经在这上面花了大约 5 个小时。我正在学习使用 Java 的入门类(class)。

这是我的代码:

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

public class WordCounter
{
private static Scanner input;

public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}

openFile();
readRecords();
closeFile();
}

public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}

public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}

public static void closeFile()
{
if (input != null)
input.close();
}
}

我尝试过的每一种方法都得到了不同的错误,最一致的错误是“找不到符号”中的文件参数

input = new Scanner(new File(file));

我也仍然不完全确定 java.io 和 java.nio 之间的区别是什么,所以我尝试使用两者的对象。我确定这是一个明显的问题,我只是看不到它。我在这里阅读了很多类似的帖子,这就是我的一些代码的来源。

我之前已经让程序编译,但随后它在命令提示符下卡住。

最佳答案

java.niojava.io 的新改进版本。您可以将其中任何一个用于此任务。我在命令行中测试了以下代码,它似乎工作正常。 “找不到符号”错误消息在 try block 中得到解决。我认为您通过实例化名为 fileFile 对象两次来混淆编译器。正如@dammina 回答的那样,您确实需要将 input.next(); 添加到 while 循环中,以便扫描器继续执行下一个单词。

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class WordCounter {

private static Scanner input;

public static void main(String[] args) {

if(args.length == 0) {
System.out.println("File name not specified.");
System.exit(1);
}

try {
File file = new File(args[0]);
input = new Scanner(file);
} catch (IOException ioException) {
System.err.println("Cannot open file.");
System.exit(1);
}

int total = 0;
while (input.hasNext()) {
total += 1;
input.next();
}

System.out.printf("The total number of words without duplication is: %d", total);

input.close();
}

}

关于java - 在java中通过命令行输入一个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com