0

Everything is fine except that it is giving a blank line in the first line of output and it is because of String a=scanner.nextLine(); but i am not able to figure out how to solve this problem of blank line occuring due to this function can anyone help?

The first input is the number of strings that will be there for the program. For each String the program should print the even-odd indexing characters of the string separated with a space.

Input:
1.2
2.Hacker
3.Rank

Output:
1.
2.Hce akr
3.Rn ak

Expected Output:
1.Hce akr
2.Rn ak

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

public class Solution {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int times=scanner.nextInt();


        for(int j=0;j<=times;j++){
            String a=scanner.nextLine();
                for(int i=0;i<a.length();i++){
                    if(i==0 || i%2==0){
                        System.out.print(a.charAt(i));
            }
        }

            System.out.print(" ");
                for(int i=0;i<a.length();i++){
                   if(i!=0 && i%2!=0){
                        System.out.print(a.charAt(i));
            }
            }
            System.out.println();

        }

    }
}

1 Answers1

-1

Don't mix nextLine and other next calls. If you want to read everything until the user presses enter, instead, do this to the scanner immediately after creating it:

scanner.useDelimiter("\r?\n");

This tells the scanner that tokens occur once every line (versus the default, which is between any whitespace).

rzwitserloot
  • 44,252
  • 4
  • 27
  • 37