karthik reddy
karthik reddy

Reputation: 71

how to resolve NoSuchElementException in java

I wrote the code as shown:

what more should I include to remove this NoSuchElementFound Exception

I've tried including HasMoreElements(),HasNextInt() but that did'nt work either

Scanner input=new Scanner(System.in);
    t=input.nextInt();
    while(t>0)
    {
        int n=input.nextInt();
        int a[]=new int[n];

please try to modify this code so that i'll not get this exception.

Upvotes: 1

Views: 53

Answers (3)

Sharad Nanda
Sharad Nanda

Reputation: 502

This exception is thrown to indicate that there are no more elements in buffer but your code is expecting one & based on the code that you have shared following two possibilities are expected:-

  1. Variable t isn't decremented : you should add 't--' as last statement in your loop & also before any continue statement that you are using.
  2. The input itself is missing the required number of integers : For this, you can take any of the approach suggested by either Matthew or Sachin. Since you are claiming hasNextInt() method isn't working, you should update the exception/error & your relevant code for better understanding of the situation.

Hope it helps!

Upvotes: 0

Matthew I.
Matthew I.

Reputation: 1813

        Scanner input = new Scanner(System.in);
        while(input.hasNext()){
            int n = input.nextInt();
            int a[] = new int[n];
            ...
        }

Upvotes: 2

RudRocks05
RudRocks05

Reputation: 13

i think you need to declare 't'

Scanner input=new Scanner(System.in);
int t=input.nextInt();
while(t>0)
{
    int n=input.nextInt();
    int a[]=new int[n];
}

Upvotes: 0

Related Questions