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


so far have set user can enter number of sentences , input each position of string array using loop.

public class test5 {     public static string inputline;      public static void main(string[] args) {         system.out.print("enter 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();         }     } } 

first , foremost code going read in 1 more time want cause array out of bounds exception. next want nextline() account new line character being entered user. try this:

system.out.print("enter number of lines:"); scanner kb=new scanner(system.in); int number=integer.parseint(kb.nextline()); string []line=new string[number]; //loop through size of array for(int i=0; < line.length; i++){     line[i]=kb.nextline(); } //now output array in reverse order need start //other end of array for(int = line.length - 1; >= 0; i--){     system.out.println(line[i]); } //always close scanner when done kb.close(); 

some useful resources scanners - https://docs.oracle.com/javase/7/docs/api/java/util/scanner.html


Comments