【问题标题】:Java: int array returning as 0sJava:返回为 0 的 int 数组
【发布时间】:2018-05-23 22:23:12
【问题描述】:

我正在尝试从文本文件中提取一个数组(请参阅下面的辐射 []),但它一直返回零。我很高兴提供 .txt。文件。

我正在使用的文本文件的整数范围为 1-200(第一个是 16),但代码似乎将文件读取为全零。关于这是怎么回事的任何想法?感谢您的见解!

public static void main (String[] args) {

    int radCtr = 0;
    Scanner scanner = new Scanner(new File("C:/Users/u23s57/Documents/4_22_18_radiation.txt"));
    while (scanner.hasNextLine()) {
        radCtr++;
        scanner.nextLine();
        }
    int [] radiation = new int [radCtr]; 
    int i = 0;
    while(scanner.hasNextInt()){
       radiation[i++] = scanner.nextInt();
    }

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

        }
    int max = getMax(radiation);
    System.out.println("Maximum Value is: "+max);

    }

【问题讨论】:

    标签: java arrays int


    【解决方案1】:
    while (scanner.hasNextLine()) {
        radCtr++;
        scanner.nextLine();
        }
    

    这个循环消耗文件中的所有行。所以当你到达这里时:

    while(scanner.hasNextInt()){
    

    没有更多的整数要读取。

    您必须:

    • 第一次循环后重新打开扫描仪。
    • 分配任意大小的数组(至少与需要的一样大)
    • 使用不需要事先知道大小的数据结构(例如List)。
    • 在不存储所有数据的情况下执行此操作。您无需全部存储即可获得最大值。

    【讨论】:

      【解决方案2】:

      由于“scanner.hasNextLine()”,您不再有任何整数了。 因此,您应该使用不同的扫描仪。

      另外,最好不要使用扫描仪而是使用缓冲阅读器。在我看来,尤其是当您要使用分隔符时(虽然我还没有看到)

      【讨论】:

        猜你喜欢
        • 2014-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-01
        • 2013-12-06
        • 2014-09-14
        • 1970-01-01
        相关资源
        最近更新 更多