Raghu Varma Manthena Raghu Varma Manthena - 3 months ago 9
Java Question

I am trying to input sentences in string arrays and display them in reverse order

So far I have set it up so that the user can enter the number of sentences and input into each position of the String array using a for loop.

public class Test5 {
public static String inputline;

public static void main(String[] args) {
System.out.print("Enter the number of lines:");
Scanner kb=new Scanner(System.in);
int number=kb.nextInt();
String []line=new String[number];
for(int i=0;i<line.length+1;i++){
line[i]=kb.next();
}
}
}

Answer

First and foremost your code is going to read in 1 more time than you want which will cause an array out of bounds exception. Next you will want to do nextLine() to account for the new line character being entered by the user. Try this:

System.out.print("Enter the number of lines:");
Scanner kb=new Scanner(System.in);
int number=Integer.parseInt(kb.nextLine());
String []line=new String[number];
//loop through only the size of the array
for(int i=0; i < line.length; i++){
    line[i]=kb.nextLine();
}
//now to output the array in reverse order you need to start from the
//other end of the array
for(int i = line.length - 1; i >= 0; i--){
    System.out.println(line[i]);
}
//always close the Scanner when done
kb.close();

Some useful resources about Scanners - https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html