简体   繁体   中英

Given an array of integers check whether there are two numbers present with given product

http://www.practice.geeksforgeeks.org/problem-page.php?pid=667 You can find Qusetion on above link .Why it is not showing me the required output. Infact I am just putting value of N which is array size, P = required output arrays values in array but after taking all values it is not showing any result.

package practice;

import java.util.Scanner;
public class Practice {

    public static void main(String a[])
    {
        Scanner in =new Scanner(System.in);
        int N = in.nextInt();
        int[] arr = new int[N];
        int P = in.nextInt();

        for(int i =0 ; i<=N ; i++){
            arr[i] = in.nextInt();
        }
        for(int j=0 ; j<arr.length;j++){
            for(int k = j+1;k>=j;++k){
                if(arr[j]*arr[k]==P){
                    System.out.println("Yes");
                }else{
                    System.out.println("No");
                }
            }
        }
    }
}

Run Time Error Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:907) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at GFG.main(File.java:14)

Instead of this for loop

for(int k = j+1;k<=j;++k)

you should have this:

for(int k = j+1;k< arr.length;++k)

in your version you start k from j+1 which is by definition larger that j hence you never get to the inside of that loop.

And also this line:

for(int i =0 ; i<=N ; i++)

Should be this:

for(int i =0 ; i< N ; i++)

That's because you are creating an array of size N but setting its values for N+1 times.

for(int k = j+1;k<=j;++k){

if J is 10, then K starts at 11 which automatically breaks the condition K <=J, and the inner loop never runs.

Your runtime error is being thrown by the Scanner. Sometimes a Java Scanner can pick up a newline character, which throws a runtime exception. Try using a BufferedReader : BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

Also, hen you are filling the array, remember that arrays go from index 0, to array.length-1 . When you create an array like: int[] arr = new int[N]; , you get a new int array of N indices. Because the first index is at 0, the final index is at N-1 . Therefore, in the for loop when k = N , the index arr[i] is 1 greater than the largest index. Using for(int i = 0; i < N; i++){...} will prevent that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM