这与NoSuchElementException有关

时间:2018-09-23 18:30:47

标签: java

我尝试了下面的代码,但是我的循环无限进行。有人可以帮忙吗

import java.util.Scanner;

public class nosuchelement {

    public static void main(String[] args) {

    sum();
    }

    static long  sum() { 
        Scanner sc=new Scanner(System.in);
        System.out.println("The length of the array is:");
        int length=sc.nextInt();
        long a[]=new long[length];
        System.out.println("Enter the numbers of the array");
        long sum=0;
        for(int i=0;i<length;i++) {
            while(sc.hasNextLong())
        {

                 sum +=sc.nextLong();
        }
        }

       return sum;
    }

}

我需要的是找到数组中给出的长型数字的总和

2 个答案:

答案 0 :(得分:0)

这些嵌套循环:

for(int i=0;i<length;i++) {
    while(sc.hasNextLong()) {
      //..
    }
}

应该是

for(int i=0;i<length && sc.hasNextLong();i++) {
  // ...
}

就目前而言,在关闭流之前,永远不要停止for循环的第一次迭代。然后for循环的所有后续迭代均不执行任何操作,因为hasNextLong()返回false。

答案 1 :(得分:0)

问题出在使用while循环时。因此,只需删除while(sc.hasNextLong())

import java.util.Scanner;

public class nosuchelement
{

public static void main(String[] args)
{

    System.out.println(sum());
}

static long sum()
{
    Scanner sc = new Scanner(System.in);
    System.out.println("The length of the array is:");
    int length = sc.nextInt();
    long a[] = new long[length];
    System.out.println("Enter the numbers of the array");
    long sum = 0;
    for (int i = 0; i < length; i++)
    {
        sum += sc.nextLong();
    }

    return sum;
}

}