1

I am trying to add values from the keyboard in my string type array. For this, I first take input the array size and then create a string array according to the size. But when I try to add values to the array it always takes size-1 values only. When tried to print the array I found that value at 0 index is always null. suppose if i give input

3
we
are 
fine

It reads only 3 we are and prints we are. but output should be we are fine. where is my fault?

 public class SparseArrays {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            int size= in.nextInt();
            String [] input= new String[size];
            for(int i=0;i<input.length;i++){
                input[i]=in.nextLine();
            }

            for(int i=0;i<input.length;i++) {
                System.out.print(input[i]);
            }
        }
    }
Yonex
  • 87
  • 9

2 Answers2

1

Because at first you read in.nextInt(); and it is in the first line, waiting to be read. Then it continues, enters into for loop and sees that there is a input[i]=in.nextLine(); method and it reads the whole line, which in your case there is nothing. So, it finishes the first round of for loop and it read the rest two. That's the reason. What you can do is read the whole line when you are reading the int size= Integer.valueOf(in.nextLine()); then your code works fine.

public static void main(String[] args) {
  Scanner in = new Scanner(System.in);
  int size= Integer.valueOf(in.nextLine());
  String [] input= new String[size];
  System.out.println(input.length);
  for(int i=0;i<input.length;i++){
    input[i]=in.nextLine();
  }

  for(int i=0;i<input.length;i++) {
    System.out.print(input[i]);
  }
}
M. Oguz Ozcan
  • 1,386
  • 12
  • 21
1

The problem is in input[i]=in.nextLine(); ,change it to input[i]=in.next(); and you will get what you want.
code :

import java.util.Scanner;
    public class bvb {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int size= in.nextInt();
        String [] input= new String[size];
        for(int i=0;i<input.length;i++){
            input[i]=in.next();
        }

        for(int i=0;i<input.length;i++) {
            System.out.print(input[i]);
        }
    }
} 

For more information read this

Lalit Verma
  • 759
  • 8
  • 22