Search code examples
javastringstdinpalindrome

Why skipping 1st iteration when reading from stdin in java?


The below program always skip the 1st iteration.It does not take any input in 1st iteration>What is wrong with this.I am ver new to java so mabe this problem could be very lame. :( below is my program

import java.util.*;
public class Solution2 {
    public static void main (String [] args){
    String str;
    int T,length,a;
    Scanner in = new Scanner(System.in);
    T = in.nextInt(); // no of test cases
    int [] oprs = new int [T];
    // taking a string 
    for(int i = 1;i <= T;i++){

         str = in.nextLine();

        int ops = 1;   
        char [] array;
        array = str.toCharArray();
        length = array.length;
        if (length % 2 == 0 ){
            int  k = 1;
            for(int j = length/2 ; j < length ;j++ ){
                if(array[length/2 - k] != array [j]){

                    a = Math.abs((int)array[length/2 - k] - (int)array[j]);
                    ops = ops + a; 
                }
                k++;
            }
            oprs [i - 1] = ops;
        }
        else{
            int k = 1;
            for(int j = (length+1)/2;j < length ; j++){
                if(array[(length-1)/2 - k ] != array [j]){
                    a = Math.abs((int)array[(length-1)/2 - k] - (int)array[j]);
                    ops = ops + a; 
                } 
                k++;  
            }
            oprs [i - 1] = ops;
        }
    }
    for(int i = 0;i < T ;i++){
        System.out.println(oprs[i]);
    }
}
}

This is the expected input and output

Sample Input
3 abc abcba abcd

output 2 0 4

This is what i am getting 3 abc abcd

It dosen't let me give the 3rd input. output 1 3 5


Solution

  • What happens is you have to capture the new line of in.nextInt (), to which must precede the following line:

    str = in.nextLine();
    

    before the FOR

    for(int i = 1;i <= T;i++){