gpt4 book ai didi

java - 如何在Java中使用 "or"?

转载 作者:行者123 更新时间:2023-12-01 11:42:13 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,允许您将两种不同类型的动物(狗和猫)送入收容所。当您运行该程序时,系统会询问您要输入哪种动物到系统中,并根据答案选择相应的文件 (.txt) 进行读取和写入。

我在通过控制台运行时选择文件时遇到问题,并且如果未输入“dog”或“cat”,则会捕获错误。

这是当前代码:

private KennelDemo() {
scan = new Scanner(System.in);
System.out.print("Are you checking a dog or cat into the kennel? Enter 'dog' or 'cat': ");

// Try to allocate the correct file to the String fileChosen

/*
* TODO
* kennel should not run if "cat" or "dog" hasn't been entered. While loop?
*/


try {
fileChosen = scan.next();
if(fileChosen == "dog")
fileChosen = dogsFile;
else if
(fileChosen == "cat")
fileChosen = catsFile;

}


catch (Exception IOException) {
System.out.println("Please enter either 'dog' or 'cat', nothing else.");

}


kennel = new Kennel();
}

进入流程应该是:

Enter dog or cat when prompted
If "cat is entered, the system reads and writes from cats.txt
If Dog is selected "dogs.txt" is read from and written to.
If neither is entered, the system catches the error and returns the user to the selection process.

发生的情况是:

When you enter "dog" or "cat", the catch error prints the error line regardless and then it tries to run Kennel();.

编辑:

以下是声明的变量:

public class KennelDemo {
private Kennel kennel; // holds the kennel
private Scanner scan; // so we can read from keyboard
private String dogsFile = "./dogs.txt"; // hardcodes file for the information regarding dogs
private String catsFile = "./cats.txt"; // hardcodes file for the information regarding cats
private String fileChosen; // String to contain the filename entered by the user and then ran with through the method KennelDemo()

对此有什么帮助吗?

谢谢。

最佳答案

在 Java 中,不应使用运算符 == 来比较字符串。请改用"dog".equals(fileChosen)

fileChosen == "dog" 永远不会为 true,因为 == 比较对象的身份,而不是它们的字符串内容。

关于java - 如何在Java中使用 "or"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29436408/

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