Home > Mobile >  How to get rid of unwanted line in output - Java
How to get rid of unwanted line in output - Java

Time:04-24

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();
    }
}

CodePudding user response:

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

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

instead of

int x = sc.nextInt();

CodePudding user response:

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!

  • Related