Home > Enterprise >  Standard Output is Empty in Java
Standard Output is Empty in Java

Time:10-04

import java.io.*;
import java.util.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int[] arr = new int[n];
        int tot=1;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        String[] strs = br.readLine().split(" ");
        for(int i=0; i<n; i  ){
            arr[i]=Integer.parseInt(strs[i]);
        }
        for(int i=0;i<n; i  ){
            tot*=arr[i];
        }
        System.out.println(tot);

   }
}

I don't know what's wrong with this code, I get standard output is empty error Help Me!

Input Given:

5 

1 2 3 4 5

CodePudding user response:

The input contains an empty line which read between s.nextInt() and br.readLine() therefore it cannot be split into numbers.

This input succeeds:

5
1 2 3 4 5
120

If the purpose of this code is to multiply n integer numbers, there's no need to read the line and then split it using extra instance of BufferedReader. Also, array int[] arr seems to be redundant.

The following code reads the count of integers n and calculates their product:

Scanner s = new Scanner(System.in);
int n = s.nextInt();

int tot=1;

for(int i=0; i < n; i  ){
    tot *= s.nextInt();
}

System.out.println("\nproduct: "   tot);

Output (integers can be read successfully regardless of whitespaces/empty lines):

5
 1 2
3 4
 5
 
product: 120

CodePudding user response:

Replace i < n with i < n && i < strs.length in both the for loops. This will ensure that the loops will be executed also as per the length of strs[] rather than just n number of times, which may cause ArrayIndexOutOfBoundsException error in the first loop e.g. for the following inputs:

5
80

your first loop will try to run from the index, 0 to 4 whereas the length of strs[] is 1 in this case i.e. the maximum allowed index, in this case, is 0.

With just i < n, your second loop body will run without ArrayIndexOutOfBoundsException but the result will be unexpected when the number of entries in br.readLine() is different from n. Since all the places in arr[] are initialized with 0 by default, the result will be zero when str.length < n; on the other hand, when str.length > n, the entries beyond the index, n - 1 will not be multiplied.

You can write i < n && i < strs.length also as i < Math.min(n, strs.length).

  • Related