Runtime Error in RECNDNOS

This code was running well in eclipse but when I tried to compile it online it showed this error.

Exception in thread “main” java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)

at java.util.Scanner.next(Scanner.java:1485)

at java.util.Scanner.nextInt(Scanner.java:2117)

at java.util.Scanner.nextInt(Scanner.java:2076)

at Main.main(Main.java:15)

CODE :
import java.util.*;
//Divya…
class Solution{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t–>0){
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
solve(a,n);
}
}
public static void solve(int a[],int n){
Map<Integer,Integer>map=new HashMap<>();
for(int i=0;i<n;i++){
if(map.isEmpty() || !map.containsKey(a[i])){
int t=a[i],p=2,count=1;
while(i+p<n){
if(a[i]==a[i+p]){
map.put(a[i],map.getOrDefault(a[i],0)+1);
p=p+2;}
else
p=p+1;
}

            }
        }
        Map.Entry<Integer,Integer> max=null;
         for (Map.Entry<Integer,Integer> entry : map.entrySet()){ 
             if(max==null || entry.getValue().compareTo(max.getValue())>0)
             max=entry;
            }
            System.out.println(max.getKey());
    }

}

LINK–CodeChef: Practical coding for everyone

It’s easy to trigger a runtime error in your code; consider the test input:

1
2
1 2

I’ve no idea how you’re getting a java.util.NoSuchElementException, though, unless you’re trying to “Run” without Providing “Custom Input”.

1 Like

@ssjgz
Thanks for suggestion ,
i have made changes and now it work fine on your test case but again it is showing same error.

import java.util.*;
//Aryan…
class Solution{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t–>0){
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
solve(a,n);
}

}
 public static void solve(int a[],int n){
     Map<Integer,Integer>map=new HashMap<>();
     for(int i=0;i<n;i++){
         if(map.isEmpty() || !map.containsKey(a[i])){
             int t=a[i],p=2,count=1;
             map.put(a[i],map.getOrDefault(a[i],0)+1);
             while(i+p<n){
                 if(a[i]==a[i+p]){
                     map.put(a[i],map.getOrDefault(a[i],0)+1);
                     p=p+2;}
                     else
                     p=p+1;
                }
             
            }
        }
        Map.Entry<Integer,Integer> max=null;
         for (Map.Entry<Integer,Integer> entry : map.entrySet()){ 
             if(max==null || entry.getValue().compareTo(max.getValue())>0)
             max=entry;
            }
            System.out.println(max.getKey());
    }

}

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

1 Like

@ssjgz

https://www.codechef.com/viewsolution/33249629

That’s a Wrong Answer, not a Runtime Error :slight_smile:

2 Likes

Ohh :sweat_smile: