Java:int数组返回0

时间:2018-05-23 22:23:12

标签: java arrays int

我试图从文本文件中拉出一个数组(参见下面的辐射[]),但它会一直返回零。我很高兴提供.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);

    }

2 个答案:

答案 0 :(得分:3)

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

此循环使用文件中的所有行。所以当你到达这里时:

while(scanner.hasNextInt()){

没有更多的内容可以阅读。

你要么:

  • 第一次循环后重新打开扫描仪。
  • 分配任意大小的数组(至少是它需要的大小)
  • 使用您不需要提前知道大小的数据结构(例如List)。
  • 不存储所有数据。您不需要将所有内容存储起来以获得最大值。

答案 1 :(得分:0)

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

另外一件事,最好不要使用扫描仪而是使用bufferedreader。在我看来,特别是当你要使用分隔符时(虽然我还没有看到)

相关问题