-3
package practice;
import java.util.*;

public class Test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of strings : ");
        int n=sc.nextInt();
        String[] str = new String[n];
        System.out.println("Enter strings : ");
        for(int i=0;i<n;i++) {          
            str[i]=sc.nextLine();
        }
        for(int i=0;i<n;i++) {          
            System.out.println(str[i]);         
        }
    }
}

This is a simple java program to get and print strings as array. But when i ran this code, if i give number of strings as 3, only 2 strings are taking as input, instead of 3. Then it directly prints the output, which is the 2 input strings. why is this happening?

Andreas
  • 138,167
  • 8
  • 112
  • 195
Navjyo
  • 5
  • This is duplicate question and has been asked many time in stack overflow. But still fyi - this is happening because you are using the same Sanner object in two places. You should first close the sc obj and the use another Scanner obj in the for loop. It will solve your problem I guess – Mushfiqur Rahman Abir Feb 10 '21 at 18:17

1 Answers1

0
import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of strings: ");
        int n = Integer.parseInt(sc.nextLine());

        String[] str = new String[n];
        System.out.println("Enter strings: ");
        for(int i=0;i<n;i++) {
            str[i]=sc.nextLine();
        }
        for(int i=0;i<n;i++) {
            System.out.println(str[i]);
        }
    }
}
Jhowa
  • 80
  • 7