用下面的代码做一个家庭作业,当我在程序运行时输入-1时, Controller 会插入字符串,即使在输入-1时不应该这样做。 do while 循环对 while 语句使用相同的代码,并且它正确退出,我不确定为什么其他代码不能按我认为应该的方式工作。我对 Java 和编程非常陌生,非常感谢任何帮助!
public static void main(String[] args) throws IOException
{
Control controller;
String userInput = "";
//InputStream fs1;
BufferedReader br1;
// int count = 0;
controller = new Control(userInput);
do
{
System.out.println("Please input a String and press Enter.");
System.out.println("Inputting -1 will terminate the building "
+ "and input process.");
br1 = new BufferedReader(new InputStreamReader(System.in));
if(!"-1".equals(userInput))
{
userInput = br1.readLine();
controller.insert(userInput);
}
System.out.print("\n"+ "User input: "+ userInput + "\n\n");
}// end do
while (!"-1".equals(userInput));
System.out.println("\nList initialized based on your inputs:\n");
controller.display();
}
这是我运行的: 运行: 请输入字符串并按 Enter 键。 输入-1将终止构建和输入过程。 5
用户输入:5
请输入字符串并按 Enter。 输入-1将终止构建和输入过程。 4
用户输入:4
请输入字符串并按 Enter。 输入-1将终止构建和输入过程。 3
用户输入:3
请输入字符串并按 Enter。 输入-1将终止构建和输入过程。 -1
用户输入:-1
根据您的输入初始化列表:
列表(第一个-->最后一个):-1 3 4 5 构建成功(总时间:6 秒)
-1 不应出现在列表中。有什么建议吗?
最佳答案
你的测试放在了错误的地方。您正在读取数据并将其放入列表中,而不对其进行测试。
if(!"-1".equals(userInput))
{
userInput = br1.readLine();
controller.insert(userInput);
}
应该是
userInput = br1.readLine();
if(!"-1".equals(userInput))
{
controller.insert(userInput);
}
关于java - if 语句表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16908935/