Ankit Prajapati
Ankit Prajapati

Reputation: 9

i m not getting correct output?

import java.util.Scanner;

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] in = new String[n];
        for (int i = 0; i < n; i++) {
            in[i] = sc.nextLine();
        }
        for (int i = 0; i < n; i++) {
            System.out.println(in[i]);
        }
    }
}

Input:

2
Ankit

Output:

Ankit

Upvotes: 0

Views: 35

Answers (2)

Pramod H G
Pramod H G

Reputation: 1613

That's because of the Scanner.nextInt method does not read the newline character in your input created by hitting "Enter" and so the call to Scanner.nextLine returns after reading that newline. There are two options to resolve this issue,

1. read the input through Scanner.nextLine and convert your input to the proper format you need

    Scanner sc = new Scanner(System.in);
    int n = Integer.parseInt(sc.nextLine());
    
    String[] in = new String[n];
    
    for (int i = 0; i < n; i++)
    {
        in[i] = sc.nextLine();
    }
    
    for (int i = 0; i < n; i++)
    {
        System.out.println(in[i]);
    }

2. Add Scanner.nextLine call after each Scanner.nextInt

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    sc.nextLine();
    
    String[] in = new String[n];
    
    for (int i = 0; i < n; i++)
    {
        in[i] = sc.nextLine();
    }
    
    for (int i = 0; i < n; i++)
    {
        System.out.println(in[i]);
    }

Upvotes: 1

Yeshwin Verma
Yeshwin Verma

Reputation: 454

the Scanner class skips next line after nextint so you can fix it by editting your code like this-

import java.util.Scanner; 
public class test {
public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    sc.nextLine();  
    String[] in=new String[n];
    for(int i=0;i<n;i++){
        in[i]=sc.nextLine();
    }
    for(int i=0;i<n;i++){
        System.out.println(in[i]);
    }
    
    }
} 

Upvotes: 0

Related Questions