简体   繁体   English

Java:int数组返回为0

[英]Java: int array returning as 0s

I'm trying to pull an array from a text file (see radiation[] below), but it keeps returning zeroes. 我正在尝试从文本文件中提取数组(请参见下面的radiation []),但是它一直返回零。 I'm happy to provide the .txt. 我很高兴提供.txt。 file. 文件。

The text file I'm using has a range of integers from 1-200 (the first is 16), but the code appears to be reading the file as all zeroes. 我正在使用的文本文件的整数范围是1-200(第一个是16),但是代码似乎正在读取全零的文件。 Any ideas about what's going on with this? 关于这是怎么回事的任何想法? Thanks for the insights! 感谢您的见解!

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);

    }
while (scanner.hasNextLine()) {
    radCtr++;
    scanner.nextLine();
    }

This loop consumes all the lines in the file. 此循环消耗了文件中的所有行。 So when you get to here: 因此,当您到达此处时:

while(scanner.hasNextInt()){

There are no more ints to read. 没有更多要读取的整数。

You either have to: 您要么必须:

  • Re-open the scanner after the first loop. 第一次循环后,请重新打开扫描仪。
  • Allocate an array of arbitrary size (that is at least as large as it needs to be) 分配任意大小的数组(至少要和所需大小一样大)
  • Use a data structure that you don't need to know the size of in advance (eg a List ). 使用不需要预先知道大小的数据结构(例如List )。
  • Do it without storing all the data. 在不存储所有数据的情况下执行此操作。 You don't need to store it all to get the maximum. 您无需全部存储即可获得最大的收益。

Because of "scanner.hasNextLine()" you don't have any integers left anymore. 由于“ scanner.hasNextLine()”,您不再有任何整数。 Therefore, you should use different scanners. 因此,您应该使用其他扫描仪。

Just another thing, it might be better to not use the scanner but bufferedreader. 另一件事,最好不使用扫描仪,而使用bufferedreader。 In my opinion especially when you're going to use delimiter (which i don't see yet though) 在我看来,尤其是当您要使用定界符时(虽然我还没有看到)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM