[英]Only else statement of if…else ladder is being executed no matter what the input. Why is this happening?
下面給出一些代碼到一個文件的升序或降序對內容進行排序wher in
是的目的Scanner
類
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();
}
但是,在執行此代碼后,無論我為變量opt
分配了什么值,我總是收到“錯誤選項”消息,並重定向到main()
方法。
為什么會這樣呢?
是否有人在其他方面有其他建議來改進此代碼?
if(opt.equals("A")||optopt.equals("a")){...}
else if(opt.equals("D")||opt.equals("d")){...}
else{...}
String
是對象,因此等於兩個字符串所需的equals
方法。
找到一個好的帖子-equals()和==有什么區別?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.