0

My program for the coding challenge produces the correct output, however, it requires me to press enter a second time for it to work. Here is the programming challenge.

It prints out the first line just fine but requires me to press enter again for it to work.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        sc.nextLine();
        for(int i = 0; i < testCases; i++){
            int size = sc.nextInt();
            sc.nextLine();
            int[] arr = new int[size];
            for(int x = 0; x < size; x++){
                arr[x] = sc.nextInt();

            }
            sc.nextLine();
            if(size > 1){
                solve(arr);
            }
            else{
                System.out.println("0");
            }
        }
    }

     private static void solve(int[] arr) {
         for(int i =0 ; i  < arr.length; i++){
             arr[i] = Math.abs(arr[i]);
         }
         Arrays.sort(arr);
         for(int i = 0; i < arr.length - 1; i++){
             int f = i + 1;
             if(arr[i] == arr[f]){
                 System.out.print((arr[i] * -1) + " " + arr[i]);
             }
         }
         System.out.println();      
     }

}
4castle
  • 28,713
  • 8
  • 60
  • 94
  • I'm not sure I understand your question. Are you trying to read in multiple integers on one line? – 4castle Oct 09 '17 at 21:44
  • Click on the link it has the input. I am trying to paste it here, however, stack over flow is autoformatting the input. http://practice.geeksforgeeks.org/problems/pairs-with-positive-negative-values/0 – Shivam Satyarthi Oct 09 '17 at 21:47
  • 1
    Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – user3437460 Oct 09 '17 at 21:58
  • It appears to be working in this [Ideone Demo](https://ideone.com/j7eTw4) (other than a few missing spaces in the output). – 4castle Oct 09 '17 at 21:58
  • 1
    This question has been asked at least a thousand times in SO. – user3437460 Oct 09 '17 at 21:59
  • @user3437460 It's not a duplicate of that. They have seemingly the opposite problem, where it requires them to press enter an extra time. – 4castle Oct 09 '17 at 21:59
  • 1
    No matter which one is duplicate of which one. The source of the problem remains the same, there are remaining tokens in the buffer of `Scanner`. – Zabuzard Oct 09 '17 at 22:16

0 Answers0