1

I am trying to create a simple String Revert program that does the following:

  • Prompts the user for an integer n
  • Creates an array of n Strings
  • Keeps reading character strings from user and stores them in the array, until the end of the array or user types "quit"
  • Prints the strings from the array in reverse order excluding empty slots

Here is my attempt so far:

-However, when i take input and make the size 4, the buffer only reads 3 strings and stops rather than 4.

import java.util.*;
import java.io.*;

class StringRevert {

    public static void main(String[] args) {

        String myArray[];

        Scanner Scan = new Scanner(System.in);
        System.out.println("Enter Number: ");
        int size = Scan.nextInt();

        myArray = new String[size];

        for(int i=0; i<myArray.length; i++) {
            myArray[i] = Scan.nextLine();
        }
    }
}
RandomMath
  • 661
  • 10
  • 27

1 Answers1

1

You need to put Scan.nextLine(); before starting of for loop.

public static void main(String[] args) {

    String myArray[];

    Scanner Scan = new Scanner(System.in);
    System.out.println("Enter Number: ");
    int size = Scan.nextInt();

    myArray = new String[size];
    Scan.nextLine();
    for(int i=0; i<myArray.length; i++) {
        System.out.println("Enter String");
        myArray[i] = Scan.nextLine();
    }
}
Pratik
  • 902
  • 4
  • 19