【问题标题】:BlueJ - BlueJ freezes when reading in from a text fileBlueJ - 从文本文件中读取时 BlueJ 冻结
【发布时间】:2017-12-07 06:37:58
【问题描述】:

因此,对于我的计算机科学课,我们必须创建一个程序,该程序将从名为“compact.txt”的文本文件中读取数据,并将其中的整数存储到 int[] 中。之后,我们必须将数字打印到终端,文本文件中包含 0,然后文本文件中不包含 0。代码编译并运行,但是当它运行时它不会向终端打印任何内容,它会完全冻结所有 BlueJ。冻结后,我什至无法从主目录中复制代码,不得不从任务管理器中强制关闭它。 FileInput 是我的班级用来读取文件的。这是我的代码:

import chn.util.*;
public class compact
{
    public static void main(String [] args)
    {
        FileInput fI = new FileInput("compact.txt");
        int[] ar = new int[100];
        String line = fI.readLine();
        fI.close();
        System.out.println(line);
        int count = 0;
        int x = 0;
        while(x < line.length())
        {
            if(!line.substring(x, x+1).equals(" "))
            {
                if(!line.substring(x + 1, x + 2).equals(" ") && !
(line.length() - 1 == x))
                {
                    ar[count] = Integer.parseInt(line.substring(x + 1, x+2));
                }
                else
                {
                    ar[count] = Integer.parseInt(line.substring(x, x+1));
                }
                count++;
            }
            x++;
        }
        System.out.print("Before: " + ar[0]);
        for(int i = 1; i < count; i++)
        {
            System.out.print(", " + ar[i]);
        }
        System.out.print("\n");
        System.out.println("After: ");
        for(int i = 0; i < count; i++)
        {
            if(ar[i] == 0)
            {
                System.out.print("");
            }
            else
            {
                if(i == count - 1)
                {
                    System.out.print(ar[i]);
                }
                System.out.print(ar[i] + ", ");
            }
        }
    }
}

这就是“compact.txt”文件中包含的内容:

0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0

【问题讨论】:

  • 所以,我得到一个StringIndexOutOfBoundsException,因为当x 等于line.length() - 1x + 1x + 2 时,超出了String 的长度。事实上,更简单的方法可能是使用String#splitScanner 并从流中读取每个字符

标签: java bluej


【解决方案1】:

所以,我得到一个StringIndexOutOfBoundsException,因为当x 等于line.length() - 1x + 1x + 2 时,超出了String 的长度。

这通常意味着你的逻辑被打破了。虽然你可以用笔纸回去然后把它搞清楚,但更好的方法可能是使用:

java.util.Scanner...

String line = "0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0";
Scanner scan = new Scanner(line);
while (scan.hasNextInt()) {
    System.out.println(scan.nextInt());
}

这将允许您从原始 String 获取每个单独的 int 元素

或者String#split...

String line = "0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0";
String[] parts = line.split(" ");

这将为您提供一个由空格分隔的Strings 数组。

从那里您可以决定如何最好地分离0s(或者,只需使用if 语句过滤输出)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多