0

In this java program, i am trying to take no of elements (n) for my String array, and then iterating that much times to insert values in my String array. But insertion does not reach till end and does not execute the last iteration. For example if n=3 then it should iterate three times(0,1,2) for insertion but it does only twice. Please help to understand.enter code here

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String[] arr=new String[60];
        System.out.println("Enter no of elements");
        int n=sc.nextInt();
        for(int i=0;i<n;i++) {
            arr[i]=sc.nextLine();
        }
        for(int i=0;i<n;i++)
        System.out.println(arr[i]);
    }
}
  • 1
    Does this answer your question? [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Turamarth Oct 16 '20 at 12:03

2 Answers2

0

The problem is related with .nextInt(); function.

When you type a number and press enter, the program receive the number and a break line character (\n). So, the next line read with .nextLine() is the '\n'.

As workaround you can place .nextLine() just below .nextInt()

public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    String[] arr=new String[60];
    System.out.println("Enter no of elements");
    int n=sc.nextInt();
    sc.nextLine(); //<-- This line
    for(int i=0;i<n;i++) {
        arr[i]=sc.nextLine();
    }
    for(int i=0;i<n;i++)
    System.out.println(arr[i]);
}
J.F.
  • 5,340
  • 7
  • 14
  • 35
0

So I assume you enter your input in a new line each time (include the value of the number of elements). What you could do is just stick with .nextLine() and then convert that to an int for your n variable, like below.

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] arr=new String[60];
        System.out.println("Enter no of elements");
        int n = Integer.parseInt(sc.nextLine());
        for(int i = 0;i < n; i++) {
            arr[i] = sc.nextLine();
        }
        for(int i = 0; i < n; i++)
        System.out.println(arr[i]);
    }
}
mjnyn
  • 1
  • 1