gpt4 book ai didi

java - 无论输入什么,都只会执行 if...else 梯形图的 else 语句。为什么会发生这种情况?

转载 作者:行者123 更新时间:2023-12-01 12:16:44 27 4
gpt4 key购买 nike

下面给出了一些代码,用于按升序或降序对文件内容进行排序,其中 inScanner 类的对象

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 方法。

找到一个好帖子 - What’s the difference between equals() and ==?

关于java - 无论输入什么,都只会执行 if...else 梯形图的 else 语句。为什么会发生这种情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26954021/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com