Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Given an integer array of size N. For each element in the array, check whether there exist a smaller element on the next immediate position of the array. If such an element exists, print that element. If there is no smaller element on the immediate next to the element then print -1.

What I have tried:

import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
List<integer> list = new ArrayList<Integer>(); //Include type (Integer) when declaring a list
while(sc.hasNext())
{
list.add(sc.nextInt());
}

for (int i = 0; i < list.size() - 1; i++) 
{ //note the "- 1" since we are looking ahead 
if (list.get(i).compareTo(list.get(i+1)) > 0) 
{
System.out.print(list.get(i)+" ");
}

else

System.out.print("-1");

}

System.out.println("-1");
}
}
}
Posted
Updated 10-Jun-19 22:29pm
Comments
Dave Kreskowiak 10-Jun-19 15:26pm    
And you have a question or a problem you forgot to describe?

1 solution

Try:

Java"
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
  public static void main (String[] args)
  {
    Scanner sc = new Scanner(System.in);
    int t=sc.nextInt();
    List<Integer> list = new ArrayList<Integer>(); 
    while(t-- > 0)
    {
      list.add(sc.nextInt());
    }
    for (int i = 0; i < list.size() - 1; i++)
    { //note the "- 1" since we are looking ahead 
      Integer current = list.get(i);
      Integer next = list.get(i+1);
      if (current > next)
      {
        System.out.print(current + " ");
      }
      else
        System.out.print("-1 ");
    }
    System.out.println("-1 ");
  }
}
 
Share this answer
 
Comments
Member 14492636 11-Jun-19 9:24am    
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.main(File.java:12)////////////////it is showing this error
Maciej Los 20-Jun-19 5:12am    
5ed!
CPallini 20-Jun-19 10:52am    
Thank you, Maciej.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900