I am using an online ide geeksforgeeks. Here, I am trying to solve this question using TreeSet and passing a Comparator object. The qusetion is as follow:
You are given an array A of size N. Replace every element with the next greatest element (greatest element on its right side) in the array. Also, since there is no element next to the last element, replace it with -1.
Do this for t test cases: Here's the code I have written:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
static Scanner sc=new Scanner(System.in);
public static void main (String[] args) {
//code
int t=sc.nextInt();
for(int i=0;i<t;i++)
display();
}
static void display(){
int n=sc.nextInt();
Set<Integer> ts=new TreeSet<Integer>(new myComparator());
int a;
for(int i=0;i<n;i++){
a=sc.nextInt();
ts.add(a);
}
Iterator itr=ts.iterator();
int count=0;
while(itr.hasNext()){
if(count==0)
continue;
else{
System.out.print(itr.next()+" ");
}
}
System.out.print(-1);
System.out.println();
}
}
class myComparator implements Comparator<Integer>{
public int compare(Integer obj1,Integer obj2){
if(obj2>obj1)
return 1;
else if(obj2<obj1)
return -1;
else
return 0;
}
}
The error that my code throws:
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 GFG.display(File.java:20)
at GFG.main(File.java:13)
Please rectify the code. Code