1

Why does this code print an extra line in the beginning, and also after accepting 2 strings it takes 0 to 2, which is 3 iterations to print the output?

enter image description here

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        for(int i=0;i<=n;i++)
        {   String s1="",s2="";
            String str;
            str= sc.nextLine();
            int l=str.length();
            for (int k=0;k<l;k++)
            {
                if (k%2==0)
                    s1=s1+str.charAt(k); 
                else if(k%2!=0)
                    s2=s2+str.charAt(k);
            }
            System.out.println(s1+" "+s2);
        }
    }
}
Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
Omkar Rane
  • 11
  • 1
  • Welcome to Stack Overflow. Please indent your code properly for readability. Your IDE can do that for you — and for us. Otherwise it’s a good question. – Ole V.V. Jul 26 '20 at 11:10

1 Answers1

0

I tweaked your solution a bit. It should work.

Scanner sc=new Scanner(System.in);
        int n=Integer.parseInt(sc.nextLine());
        for(int i=0;i<n;i++)
        {    String s1="",s2="";
            String str;
            str= sc.nextLine();
            int l=str.length();
            for (int k=0;k<l;k++)
            {
                if(k%2==0)
                    s1=s1+str.charAt(k);
                else if(k%2!=0)
                    s2=s2+str.charAt(k);
            }
            System.out.println(s1+" "+s2);
        }
        sc.close();

Edit: Also, you were iterating (n+1) times