Skip to content
Advertisement

java for loop early termination

This is the first half of my java program- to input certain values. I noticed that the first ‘for loop’which takes in values of the answer key is getting terminated after 2 or 3 iterations instead of the expected 5, and I have, so far, had no luck in figuring out why. Any help would be appreciated, thanks!

public class quizscores
{ public void main()throws IOException
    { BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("enter no of participants");
        int n=Integer.parseInt(br.readLine());
        char arr[][]=new char[n][5];
        
        System.out.println("Please enter answer key");
        char ans[]=new char[5];

        for(int i=0;i<5;i++) //referring to this for loop
        {
         ans[i]=(char)(br.read());
        }
        
        System.out.println("please enter answers of participants ");
        for(int i=0;i<n;i++)
        {for(int j=0;j<5;j++)
            {arr[i][j]=(char)(br.read());
            }
       }
      

Advertisement

Answer

BufferedReader.read() method reads one character at a time so what will happen in your case that it will read the empty space or the enter when you are giving input on a new line try giving answer key input on a single line without spaces.

    System.out.println("Please enter answer key");
    char ans[]=new char[5];

    for(int i=0;i<5;i++) //referring to this for loop
    {
     ans[i]=(char)(br.read());
    }

Sample I/O
Please enter the answer key
ABCDE

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement