java if 语句不打破“for 循环”

发布于 2024-12-24 03:36:21 字数 1054 浏览 0 评论 0原文

我是java新手,但我认为这几周我自学得很好。但现在我陷入了这个循环。

这是我的一个班级的一个方法。为了帮助我进行调试,我在该方法中添加了“myString”字符串和“语法”列表,以演示正在发生的情况并保持简单,至少目前如此。

public void getIndex(){
    String myString = "2 2 + 3 5";
    String[] syntax = myString.split(" ");

    for (int index = 0; index < syntax.length; index++){
        System.out.println("current index is: " + index);
        System.out.println("It has: " + syntax[index]);
        // these print statements are made to help me debug
        if (syntax[index] == "+"){
            indexNeeded = index;
            break;
        }
    }
    System.out.println("Index Needed: " + indexNeeded);   

正如您在循环中看到的,当列表元素“语法”为“+”时,我想中断“for 循环”。 (我在这里显示“+”,但它可以是实际程序中的任何内容。)

这是运行此方法时的输出:

current index is: 0
It has: 2
current index is: 1
It has: 2
current index is: 2
It has: +
current index is: 3
It has: 3
current index is: 4
It has: 5
Index Needed: 0

当找到“+”时,循环应该停止,但似乎“if 语句” ”根本不起作用,因此“indexNeeded”没有改变。

这是一个简单的方法,但我在这里做错了什么?

I am newbie in java but I think I have done well teaching myself in these few weeks. But now I am stuck at this loop.

Here is a method from one of my class. To help me debug, I have added "myString" string and "syntax" list inside this method to demonstrate what is happening and to keep it simple, at least for now.

public void getIndex(){
    String myString = "2 2 + 3 5";
    String[] syntax = myString.split(" ");

    for (int index = 0; index < syntax.length; index++){
        System.out.println("current index is: " + index);
        System.out.println("It has: " + syntax[index]);
        // these print statements are made to help me debug
        if (syntax[index] == "+"){
            indexNeeded = index;
            break;
        }
    }
    System.out.println("Index Needed: " + indexNeeded);   

As you can see inside the loop, I want to break the "for loop" when the element of the list, "syntax" is "+".
(I am showing "+" here but it can be anything in the actual program.)

Here is the output, when run this method:

current index is: 0
It has: 2
current index is: 1
It has: 2
current index is: 2
It has: +
current index is: 3
It has: 3
current index is: 4
It has: 5
Index Needed: 0

The loop should have stopped when it found "+" but it seems that "if statement" is not working at all, and hence "indexNeeded" hasn't changed.

It's a simple method but what am I doing wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

_失温 2024-12-31 03:36:21

您正在尝试将字符串与 == 进行比较。这是不行的,你需要使用 .equals():

change:

syntax[index] == "+"

to

syntax[index].equals("+")

== 仅当两个对象引用同一个实例时才返回 true。 equals() 当字符串内容相同时返回 true。这就是你想要的。

You're trying to compare strings with ==. That doesn't work, you need to use .equals():

change:

syntax[index] == "+"

to

syntax[index].equals("+")

== only returns true when both objects refer to the same instance. equals() will return true when the contents of the string are the same. This is what you want.

节枝 2024-12-31 03:36:21

替换

if (syntax[index] == "+"){

if (syntax[index].equals("+")){

当您尝试 == 时,它会比较引用,并且 syntex[index] 并不引用文字 "+" 所在的同一位置。所以他们并不平等。

// If syntax[index] get '+' value from somewhere but not literal
if(syntax[index] == "+" ) // is false
// right way is 
if(syntax[index].equals("+")) // is true

// If syntax[index] get '+' value from literal
syntax[index] = "+";
if(syntax[index] == "+" ) // is true
// This approach is faster but has mentioned above has limitations.

当你这样做时,它实际上会比较内容。

Replace

if (syntax[index] == "+"){

with

if (syntax[index].equals("+")){

When you are trying == it comparing the references and syntex[index] is not referring to same location where literal "+" is. So they are not equal.

// If syntax[index] get '+' value from somewhere but not literal
if(syntax[index] == "+" ) // is false
// right way is 
if(syntax[index].equals("+")) // is true

// If syntax[index] get '+' value from literal
syntax[index] = "+";
if(syntax[index] == "+" ) // is true
// This approach is faster but has mentioned above has limitations.

When you do equals it actually compares the content.

北斗星光 2024-12-31 03:36:21

您应该这样写:

syntax[index].equals("+")

"+" 是对字符串的引用,syntax[index] 是另一个。但在这里您想要比较对象本身,而不是它们的引用。

如果您采用任何类的两个对象 aba == b 将测试引用相同。测试它们是否“相同”被编写为a.equals(b)

您应该阅读 Java 的 .equals() 文档仔细看,它是理解的基础部分。

You should write:

syntax[index].equals("+")

"+" is a reference to a String, and syntax[index] is another. But here you want to compare the objects themselves, not their references.

If you take two objects a and b of whatever class, a == b will test that the references are the same. Testing that they are "the same" is written a.equals(b).

You should read Java's .equals() documentation carefully, it is a fundamental part to understand.

在你怀里撒娇 2024-12-31 03:36:21

对于字符串,你需要做

syntax[index].equals("+")

for String, you need to do

syntax[index].equals("+")
对你再特殊 2024-12-31 03:36:21

如果你想比较字符串的值,你需要使用.equals(),但如果你想比较引用,你需要使用运算符==。这是新手常见的错误。

花点时间看看两者之间的区别:

syntax[index] == "+"

"+".equals(syntax[index])

它的顺序是您不允许在 syntax[index] 中出现可能的空指针

If you want to compare the value of a String you need to use .equals() but if you want to compare references you use the operator ==. That a common mistake with newbies.

Take a minute and see the difference between:

syntax[index] == "+"

and

"+".equals(syntax[index])

it that order you don't allow possible null pointer in syntax[index]

暗喜 2024-12-31 03:36:21

这是一种有趣且有教育意义的方法来解决您的问题。添加对 的调用String.intern() 添加到您的方法中,它将正常工作。让你的朋友惊叹不已! :)

public int getIndex()
{
    String myString = "2 2 + 3 5";
    String[] syntax = myString.split(" ");
    int indexNeeded = -1;
    for (int index = 0; index < syntax.length; index++)
    {
        System.out.println("current index is: " + index);
        System.out.println("It has: " + syntax[index]);
        // these print statements are made to help me debug
        if (syntax[index].intern() == "+")
        {
            indexNeeded = index;
            break;
        }
    }
    return indexNeeded;
}

请注意,从方法返回值比使用类范围的变量更好。类范围的变量应该保留用于可以被视为对象属性的数据。 indexNeeded 不符合该描述,对于 int 来说这是一个糟糕的名称 - 听起来它应该是一个 boolean

Here's a fun, educational way to fix your problem. Add a call to String.intern() to your method and it will work fine. Amaze your friends! :)

public int getIndex()
{
    String myString = "2 2 + 3 5";
    String[] syntax = myString.split(" ");
    int indexNeeded = -1;
    for (int index = 0; index < syntax.length; index++)
    {
        System.out.println("current index is: " + index);
        System.out.println("It has: " + syntax[index]);
        // these print statements are made to help me debug
        if (syntax[index].intern() == "+")
        {
            indexNeeded = index;
            break;
        }
    }
    return indexNeeded;
}

Note that it is better to return a value from a method than it is to use variables with class scope. Class-scoped variables should be reserved for data that can be considered a property of the object. indexNeeded doesn't meet that description, and it's a poor name for an int - it sounds like it should be a boolean.

苏大泽ㄣ 2024-12-31 03:36:21

Java 中的相等性检查有两种形式。

相等运算符“==”检查两个变量是否引用同一个对象。在您的情况下,此测试失败,因为尽管它们的内容相同,但您引用的是两个不同的字符串对象。

.equals() 方法可用于每个 Java 对象,并提供可扩展的相等检查。对于字符串,请考虑以下事项:

"+".equals("+") // evaluates to true

回到相等运算符:

"+" == "+" // evaluates to false

请参阅 此页面了解更多详细信息。

Equality checks in Java come in two forms.

The equality operator "==" checks to see if two variables refer to the same object. In your case, this test fails because, though their content is the same, you're referring to two different string objects.

The .equals() method is available on every Java object and provides extensible equality checking. In the case of Strings, consider the following:

"+".equals("+") // evaluates to true

going back to the equality operator:

"+" == "+" // evaluates to false

See this page for more detail.

属性 2024-12-31 03:36:21

使用返回;而不是打破;
这对我有用

Use return; instead of break;
it works for me

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文