0

I am writing a method that takes user input from stdin and prints to stdout. It is supposed to read the number of strings from the first line, which is the number of test cases. Then for each string it should print the characters at the even indices, two spaces, then the characters at the odd indices. For Example:

Input: (without the blank lines, for some reason question formatting displays this way..)

2

abcd 

efgh 

Expected Output: (without the blank lines, for some reason question formatting displays this way..)

ac bd

ag fh

However I am having issues with an extra line printing before the strings print in the output, there should only be a new line for each string/test case. This is my current method and output(with the same input as above):

public class Solution {

    public static void main(String[] args) {
        String S = null;
        int N = 0;
        int T = 0;
        Scanner scans = new Scanner(System.in);
        T = scans.nextInt();
        for (int i = 0; i <= T; i++) { //To read through test cases
            S = (scans.nextLine());
            N = S.length();
            for (int j = 0; j < N; j = j + 2) { //even indices
                System.out.print(S.charAt(j));
            }
            System.out.print("  ");
            for (int k = 1; k < N; k = k + 2) { //odd indices
                System.out.print(S.charAt(k));
            }
            System.out.println(); //Unsure where to put this so that it will only create a new line when necessary...
        }
    }       
}

Current Output: (without the additional blank lines, for some reason question formatting displays this way..)

//Getting an extra line here at the beginning


ac bd 

ag fh

I am a beginner, please give me pointers as how to better ask this question if needed. Also wondering how to format question so that I can type things on separate lines without a line between each.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • _for some reason question formatting displays this way_ Learn how to use [markdown](https://stackoverflow.com/editing-help). – Abra Apr 14 '21 at 13:56
  • `T = scans.nextInt();` After this line (and before the `for` loop), add this: `scans.nextLine()` – Abra Apr 14 '21 at 13:58
  • Thank you so much! I tried that before but was putting it within the first for loop so wasn't working. Working now! I will read up on markdown. – newToCoding Apr 14 '21 at 14:01

0 Answers0