-1

I'm trying to print pairs of elements whose sum is matched with the input. But it shows an error in the line int size=s.nextInt();.

how can I fix this?

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner s=new Scanner(System.in);
    System.out.println("Enter the size of the array");
    int size=s.nextInt();
    int arr[]=new int[size];
    getElements(arr,size);
    System.out.println("Enter the sum data");
    int sum=s.nextInt();
    printPairs(arr,sum);
  }
  static void getElements(int a[],int sizee){
    //have the logic for accepting input numbers
    Scanner s=new Scanner(System.in);
    System.out.println("Enter "+sizee+" elements");

    for(int i=0;i<a.length;i++){

      a[i]=s.nextInt();
      }

  }
  static void printPairs(int a[],int data){
    //have the logic for printing pair information 
    for (int i=0;i<a.length;i++){
       int first = a[i];
      for (int j=i+1;j<a.length;j++){
        int second = a[j];
        if(first+second == data)
        System.out.println("("+first+", "+second+")");
      }
    }
  }
}

Exception:

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:7)

Input: this is the expected input

Sivaani N
  • 7
  • 5

1 Answers1

0

Making another scanner is problematic (Not sure if scanner buffers, but if it does, this code wouldn't work). Pass it along or create one as a field in your class.

Other than that, there's nothing inherently wrong with this code: The error is what you get because that's what's happening: You are passing as input, say:

2 1 3

and then ending the input entirely (for example by hitting a certain keycombo, or you're providing the input via file, i.e. with java -cp . com.foo.YourApp <inputs.txt and the file ends there. Your app would need another number (representing the sum) in this example.

rzwitserloot
  • 65,603
  • 5
  • 38
  • 52