我在使用 FileReader 将 txt 文件写入数组 (Java) 时遇到问题,我做错了什么?

发布于 2024-08-28 13:00:46 字数 786 浏览 5 评论 0原文

Scanner s = null;
    try {
        s = new Scanner(new BufferedReader(new FileReader("rates.txt")));
            for (int i=0; i<9; i++){
                while(s.hasNext()){rates[i] = s.next();}
                System.out.println(rates[i]);
            }
    }catch (IOException e){
        System.out.println(e);
    }
    finally {
        if (s != null) {
            s.close();
        }
    }

当我运行此代码时,它会读取 txt 文件中的最后一个字符块,将它们放入 rates[0] 中,将 null 保留在 1-9 中。我不确定为什么它首先读取我的文件末尾。 txt 的内容如下。

USD 1.34

EUR 1.00

JPY 126.28

GBP 0.88

INR 60.20

它读取 60.20,这是它在数组中记录的所有内容。任何帮助将不胜感激。我想我可以给你运行这段代码的结果:

run:
60.20
null
null
null
null
null
null
null
null
BUILD SUCCESSFUL (total time: 0 seconds)
Scanner s = null;
    try {
        s = new Scanner(new BufferedReader(new FileReader("rates.txt")));
            for (int i=0; i<9; i++){
                while(s.hasNext()){rates[i] = s.next();}
                System.out.println(rates[i]);
            }
    }catch (IOException e){
        System.out.println(e);
    }
    finally {
        if (s != null) {
            s.close();
        }
    }

When I run this code, it reads the last chunk of characters in my txt file, places them in rates[0], sticks null in 1-9. I'm not sure why it's reading the end of my file first. The contents of the txt are below..

USD 1.34

EUR 1.00

JPY 126.28

GBP 0.88

INR 60.20

It reads the 60.20, which is all it is recording in the array. Any help would be appreciated. I guess I could give you the results of running this code:

run:
60.20
null
null
null
null
null
null
null
null
BUILD SUCCESSFUL (total time: 0 seconds)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

初心 2024-09-04 13:00:46
while(s.hasNext()){rates[i] = s.next();}

用简单的英语来说,这意味着:当还剩下令牌时,将下一个令牌放入 rates[i] 中。

因此,它将把第一个令牌放入 rates[i] 中,然后将下一个令牌放入 rates[i] 中,然后将下一个令牌放入 rates[i]< /code>,...,最后一个标记进入 rates[i]。由于 i 未修改,因此所有值都写入数组的同一元素,覆盖之前读取的值。

while(s.hasNext()){rates[i] = s.next();}

In plain english, this says: While there are tokens left, put the next token into rates[i].

So it will put the first token into rates[i], then the next token into rates[i], then the next token into rates[i], ..., and finally the last token into rates[i]. Since i is not modified, all the values are written into the same element of the array, overwriting the previously read values.

柳絮泡泡 2024-09-04 13:00:46

我建议:

  • 使用 List 而不是数组
    • 更灵活,更容易使用,利用 Java 集合框架等
  • 不将货币符号和数字汇率全部存储在一个混合包中
    • ...但是使用类来封装该对
  • 使用 Scanner.nextDouble() 读取数字汇率(大概您需要将其转换为 double代码>无论如何)

所以,像这样:

List<ExchangeRate> allRates = new ArrayList<ExchangeRate>();
while (sc.hasNext()) {
    String symbol = sc.next();
    double rate = sc.nextDouble();
    allRates.add(new ExchangeRate(symbol, rate));
}

注意如何:

  • 您不再需要知道在数组中分配多少个元素
  • 符号和速率不会全部扔进一个混合包
  • List.add 表示不需要您跟踪和管理的计数器
    • 即您原来问题中的错误!

I recommend:

  • Using List instead of array
    • More flexible, much easier to work with, takes advantage of Java Collections Framework, etc
  • Not storing the currency symbol and the numeric exchange rate all in one mixed bag
    • ...but using a class to encapsulate the pair
  • Using Scanner.nextDouble() to read the numeric exchange rate (which presumably you'll want to convert to double anyway)

So, something like this:

List<ExchangeRate> allRates = new ArrayList<ExchangeRate>();
while (sc.hasNext()) {
    String symbol = sc.next();
    double rate = sc.nextDouble();
    allRates.add(new ExchangeRate(symbol, rate));
}

Note how:

  • You no longer need to know how many elements to allocate in an array
  • The symbol and the rate aren't all thrown into one mixed bag
  • List.add means no counter that you need to keep track of and manage
    • i.e. the bug in your original question!
维持三分热 2024-09-04 13:00:46

我认为问题在于包含 while 循环的第 5 行读取整个文件输入。因此,您在第一次 for 循环迭代中读取了整个文件,其中 i = 0;下次您的 for 循环时,就没有任何内容可供读取了。

你可能想要这样的东西:

List rates = new ArrayList();
while (s.hasNext()) {
      rates.add(s.next());
}

I think the problem is that line 5, which contains your while loop, reads the entire file input. So you read your entire file on the first for loop iteration where i = 0; The next time your for loop there is nothing left to read.

You probably want something like this instead:

List rates = new ArrayList();
while (s.hasNext()) {
      rates.add(s.next());
}
栖迟 2024-09-04 13:00:46

另一个潜在问题:FileReader 使用平台默认编码。这可能适合处理用户提供的文件,但如果这些文件是应用程序的一部分,则当应用程序在具有不兼容的默认编码的系统上运行时,它们可能会被损坏(不,仅使用 ASCII 字符不会不能完全保护您免受这种情况的影响)。

为了避免这个问题,请改用 new InputStreamReader(new FileInputStream(filename),encoding) - 并意识到您实际上必须为您的文件选择一个encoding

One other potential problem: FileReader uses the platform default encoding. This can be appropriate to process user-supplied files, but if the files are part of the application, they can get corrupted when the application is run on a system with an incompatible default encoding (and no, using only ASCII characters does not protect you completely against this).

To avoid the problem, use new InputStreamReader(new FileInputStream(filename), encoding) instead - and realize that you actually have to pick an encoding for your file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文