Search code examples
javaarrayssortingbufferedreaderstring-length

Output issues: Passing from BufferedReader to array method


I've compiled and debugged my program, but there is no output. I suspect an issue passing from BufferedReader to the array method, but I'm not good enough with java to know what it is or how to fix it... Please help! :)

 public class Viennaproj {

 private String[] names;
  private int longth;
  //private String [] output; 

  public Viennaproj(int length, String line) throws IOException
  {
     this.longth = length;
     this.names = new String[length];
     String file = "names.txt";
     processFile("names.txt",5);
     sortNames();
  }


 public void processFile (String file, int x) throws IOException, FileNotFoundException{
BufferedReader reader = null;

try {
//File file = new File("names.txt");
reader = new BufferedReader(new FileReader(file));

String line;
while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}
}

   }


  public void sortNames()
  {
     int counter = 0;
     int[] lengths = new int[longth];
     for( String name : names)
     {
        lengths[counter] = name.length();
        counter++;
     }


     for (int k = 0; k<longth; k++)
     {
        int counter2 = k+1;
        while (lengths[counter2]<lengths[k]){
         String temp2;
         int temp;
         temp = lengths[counter2];
         temp2 = names[counter2];
         lengths[counter2] = lengths[k];
         names[counter2] = names[k];
         lengths[k] = temp;
         names[k] = temp2;

         counter2++;
        }

     }

  }


  public String toString()
  {
     String output = new String();

     for(String name: names)
     {
        output = name + "/n" + output;
     }

     return output;
  }


  public static void main(String[] args)
  {
    String output = new String ();
    output= output.toString();
     System.out.println(output+"");

  }


}

Solution

  • In Java, the public static void main(String[] args) method is the starting point of the application.

    You should create an object of Viennaproj in your main method. Looking at your implementation, just creating an object of Viennaproj will fix your code.

    Your main method should look like below

    public static void main(String[] args) throws IOException
    {
     Viennaproj viennaproj = new Viennaproj(5, "Sample Line");
     String output= viennaproj.toString();
     System.out.println(output);
    }
    

    And, if you are getting a FileNotFound exception when you execute this, it means that java is not able to find the file.

    You must provide complete file path of your file to avoid that issue. (eg: "C:/test/input.txt")