Fupeng Zhao
Fupeng Zhao

Reputation: 1

How to get rid of unwanted line in output - Java

The goal of this program is to print its even-indexed and odd-indexed characters as space-separated strings on a single line. But for some reason when I go to output, there's always an extra line shown here.

import java.util.*;

public class program1{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in); // Init Scanner
        int x = sc.nextInt();
        for (int i = 0; x >= i; i++){ //Loops 
            String word = sc.nextLine();
            String temp1 = "", temp2 = "";
            for (int j = 0; word.length() > j; j++){
                if (j % 2 == 0){
                    temp1 += word.charAt(j);
                } else if (j % 2 != 0){
                    temp2 += word.charAt(j);
                }
            }
            System.out.println(temp1 + " " + temp2);
        } sc.close();
    }
}

Upvotes: 0

Views: 54

Answers (2)

Fupeng Zhao
Fupeng Zhao

Reputation: 1

Using sc.nextLine() method I changed for (int i = 0; x >= i; i++){ // Loops to for (int i = 0; x > i; i++){ // Loops Which fixed the java.util.NoSuchElementException: No line found error

Using int x = Integer.parseInt(sc.nextLine()); method I also have to change I changed for (int i = 0; x >= i; i++){ // Loops to for (int i = 0; x > i; i++){ // Loops as it is making me input three strings instead of the desired two.

Thank you to all the people who helped me!

Upvotes: 0

Levon Minasian
Levon Minasian

Reputation: 571

The simplest solution to get rid of the "extra line" is doing

int x = Integer.parseInt(sc.nextLine());

instead of

int x = sc.nextInt();

Upvotes: 1

Related Questions