简体   繁体   English

java输入字符串并在输入“ stop”时停止

[英]java input string and stop when 'stop' is entered

this is my code and I have a do-while loop which should carry on unless the string "text" entered is "stop". 这是我的代码,我有一个do-while循环,除非输入的字符串“ text”为“ stop”,否则该循环应继续进行。 However when I compile the code it doesnt stop and stuck in an infinite loop. 但是,当我编译代码时,它不会停止并陷入无限循环。 Pease help. 请帮助。 Thanks. 谢谢。

import java.io.*;

public class input
{
    public static void main(String[] argv) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
        String text = "";  
        do
        {
            System.out.println("Please enter a string: ");
            text = br.readLine(); 
            System.out.println(text);
        }
        while (text != "stop");
    }
}

Try replacing text != "stop" by !text.equals("stop") 尝试用!text.equals("stop")替换text != "stop"

!= is a reference equality test, .equals() is a logical equality test. !=是参考相等测试, .equals()是一个逻辑相等测试。 Two strings can be different objects and still be logicaly equals (same content in this case). 两个字符串可以是不同的对象,仍然是逻辑等于(在这种情况下相同的内容)。

You are comparing strings with != . 您正在将字符串与!=进行比较。 That does not work in Java. 在Java中不起作用。 You should use equals() to compare strings: 您应该使用equals()比较字符串:

while (!text.equals("stop"));

Note that == and != on objects compare the references - ie, if you use those operators on non-primitive variables, you are checking if the variables refer to the same object, and not if the content of those objects is the same. 请注意,对象上的==!=比较引用 - 即,如果在非原始变量上使用这些运算符,则检查变量是否引用同一对象,而不是这些对象的内容是否相同。

Replace 更换

while (text != "stop")

with

while (!text.equals("stop"))

You cannot compare strings using == . 您不能使用==比较字符串。 Use equals : while(!"stop".equals(text)) . 使用equalswhile(!"stop".equals(text))

Also since it comes from the user input, you might want to compare ignoring the case, you can use equalsIgnoreCase . 此外,由于它来自用户输入,您可能想要比较忽略大小写,您可以使用equalsIgnoreCase

All posters are right: you should use String.equals(). 所有海报都是对的:你应该使用String.equals()。

Also you should complete understand String handling in Java. 您还应该完全理解Java中的字符串处理。 You will need it everywhere. 您将在任何地方都需要它。

Even that String.equals should be used Java offers some "magic", that works even with your comparison. 即使是String.equals应该使用Java提供一些“魔术”,即使你的比较也可以。 Keep learning ! 保持学习 !

public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String text = "";
        "stop".intern();
        do {
            System.out.println("Please enter a string: ");
            text = br.readLine().intern();
            System.out.println(text);
        } while (text != "stop");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM