java - Illegal start of expression string -


i trying make program reverses text lines in file. still learning java , new this. program erroring because made variable inside loop , tried access outside. tried adding preffix "public" before declaring string variable when try compile it points "public" , says illegal start of expression. can please tell me why erroring , or how fix it.

    import java.io.*;     import java.util.*;      public class filereverser     {      public static void main(string[] args)      throws filenotfoundexception {     scanner console = new scanner(system.in);     system.out.print("file reverse: ");     string inputfilename = console.next();      system.out.print("output file: ");     string outputfilename = console.next();      filereader reader = new filereader(inputfilename);     scanner in = new scanner(reader);     printwriter out = new printwriter(outputfilename);      int number = 0;      while (in.hasnextline())     {         string line = in.nextline();         public string[] lines;         lines[number] = line;         number++;     }     int subtract = 0;     (int i;i>lines.length;i++)     {         out.println(lines[(lines.length-subtract)]);         subtract++;     }      out.close();      }     } 

problems:

  • you're declaring lines public modifier, instance/static variables, not local variables.
  • you're never initializing lines
  • you're trying use lines outside scope (which while loop)
  • you're trying use i without initializing it, here:

    for (int i;i>lines.length;i++) 
  • your if condition wrong way round; want continue while i less lines.length
  • subtract 0, accessing lines[lines.length - subtract] throw exception (as it's outside bounds of array)

you can fix these following code:

// see note later string[] lines = new string[1000];  while (in.hasnextline()) {     string line = in.nextline();     lines[number] = line;     number++; } // rid of subtract entirely... , start off @ "number" // rather lines.length, there'll bunch of null elements (int = number - 1; >= 0; i--) {     out.println(lines[i]); } 

now work 1000 lines - it's pain have limitation. better use list<string>:

list<string> lines = new arraylist<string>(); while (in.hasnextline()) {     lines.add(in.nextline()); } 

then you'd need use size() instead of length, , use get instead of array indexer access values - cleaner code imo.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -