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?