0

Given below is some code to sort the contents of a file in ascending or descending order wher in is an object of the Scanner class

public void sortFile(String fileName)throws IOException
{
    FileReader fin=new FileReader("C:\\File Handling\\"+fileName+".txt");
    BufferedReader bin=new BufferedReader(fin);

    String[] str=new String[100];

    int i=0;
    while((str[i]=bin.readLine())!=null)
        i++;

    Comparator<String> c=Collections.reverseOrder();

    System.out.println("\nIf you want to sort in descending order, enter A");
    System.out.println("If you want to sort in ascending order, enter D");
    System.out.println("Using any other characters or strings will produce an error and exit his method\n");

    String opt=in.next();
    if(opt=="A"||opt=="a")
        Arrays.sort(str,0,i);
    else if(opt=="D"||opt=="d")
        Arrays.sort(str,0,i,c);
    else
    {
        System.out.println("Wrong option");
        main();
    }

    FileWriter fout=new FileWriter("C:\\File Handling\\"+fileName+".txt");
    BufferedWriter bout=new BufferedWriter(fout);
    PrintWriter pout=new PrintWriter(bout);

    for(i=0;i<str.length;i++)
    {
        if(str[i]!=null)
            pout.println(str[i]);
    }

    pout.flush();
    pout.close();
}

However upon execution of this code, no matter what value I assign to the variable opt, I always get a message of "Wrong option" and get redirected to the main() method.

Why is this happening?

Does anyone have any other suggestions to improve this code in any other aspect?

  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Pradeep Simha Nov 16 '14 at 05:14

1 Answers1

1
if(opt.equals("A")||optopt.equals("a")){...}
else if(opt.equals("D")||opt.equals("d")){...}
else{...}

String is object so for equaling two string's required equals method.

Find a good post - What’s the difference between equals() and ==?

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • Yes, you need to use the equals() method instead of using == to compare strings. == works for primitives, or for testing to see if two objects are the same instance. – Jamie Nov 16 '14 at 05:15