简体   繁体   English

if 语句意外地在 for 循环内无限循环

[英]If statement unexpectedly loops infinitely inside for loop

input: "Who lives in a pineapple under the sea?"输入:“谁住在海底的菠萝里?” expected output: "Who sevil in a elppaenip rednu the sea?"预期的 output:“谁在 elppaenip rednu 大海中撒谎?” (reverse size 5 and above words) (反尺寸5及以上字)

I think the if statement is the problem but I don't know why it's not working.我认为 if 语句是问题,但我不知道为什么它不起作用。 I tried using the code from the if statement block inside the main method and it works fine.我尝试在 main 方法中使用 if 语句块中的代码,它工作正常。

public class Testing {

    public static void main(String[] args) {
        String sentence = "Who lives in a pineapple under the sea?"; 
        System.out.println(spinWords(sentence)); 
    }
    
      public static String spinWords(String sentence) {
        String[] words = sentence.split(" "); 
        int length = words.length; 
        String spinned = ""; 
        for (int i = 0; i < length; i++) {
            String word = words[i];  
            int wlength = word.length(); 
            if (wlength > 4) {  
                String reversed = ""; 
                for (i = wlength - 1; i >= 0; i--) {
                    reversed += "" + word.charAt(i); 
                }
                spinned += reversed + " ";
            } else {
              spinned += word + " "; 
            }
        }
        spinned = spinned.trim(); 
        return spinned; 
      }
}

This is my first stack overflow question btw and I don't really know what I'm doing.这是我的第一个堆栈溢出问题,顺便说一句,我真的不知道自己在做什么。 I would also love to see better implementations of this code ( for learning purposes ), thanks.我也希望看到此代码的更好实现(用于学习目的),谢谢。

Replace the "if" block with below code.用下面的代码替换“if”块。 You were using the variable "i" which is used by the first "for" loop.您正在使用第一个“for”循环使用的变量“i”。 This caused the infinite loop.这导致了无限循环。

    if (wlength > 4) {  
        String reversed  = "";
         for(int j = 0; j < wlength; j++) {
             reversed = word.charAt(j) + reversed;
         }
         spinned += reversed + " ";
    } else {
      spinned += word + " "; 
    }

The issue in your code is the duplicate use of the local variable i as others have pointed out.您的代码中的问题是重复使用局部变量i正如其他人所指出的那样。 Typically you never want a nested loop counter to use the same variable name as the outer loop counter.通常,您永远不希望嵌套循环计数器使用与外部循环计数器相同的变量名。

There is a reason why for (int i = wlength - 1; i >= 0; i--) is a compilation error (with the int declaration added). for (int i = wlength - 1; i >= 0; i--)是编译错误(添加了int声明)是有原因的。 Instead simply use another variable name:而是简单地使用另一个变量名:

for (int j = wlength - 1; j >= 0; j--)

This will fix the error in the code.这将修复代码中的错误。 However, since you asked for other implementations I thought I would show another option using StringBuilder , which I believe is easier to read:但是,由于您要求其他实现,我想我会使用StringBuilder显示另一个选项,我相信它更容易阅读:

public static void main(String[] args) {
    String sentence = "Who lives in a pineapple under the sea?";
    System.out.println(spinWords(sentence));
}

public static String spinWords(String sentence) {
    String[] words = sentence.split(" ");
    StringBuilder sb = new StringBuilder();

    for (String str : words) {
        if (str.length() >= 5) {
            sb.append(new StringBuilder(str).reverse());
        } else {
            sb.append(str);
        }
        sb.append(" ");
    }

    return sb.toString().trim();
}

StringBuilder is often used when concatenating a String inside of a loop, see this answer .在循环内连接String时,通常使用StringBuilder请参阅此答案

Additionally, StringBuilder has the reverse() method which you can use to reverse individual words instead of using a nested loop.此外, StringBuilder具有reverse()方法,您可以使用它来反转单个单词,而不是使用嵌套循环。 You then just use toString to convert the StringBuilder object into a String .然后,您只需使用toStringStringBuilder object 转换为String

Lastly, I used an enhanced for loop of for (String str: words) which allows you to loop directly on the String values instead of needing to use a loop counter.最后,我使用了for (String str: words)的增强 for 循环,它允许您直接在String值上循环,而不需要使用循环计数器。

Here's a one-liner:这是一个单行:

public static String spinWords(String sentence) {
    return Arrays.stream(sentence.split(" "))
      .map(word -> word.length() < 5 ? word : new StringBuilder(word).reverse().toString())
      .collect(Collectors.joining(" "));
}

See live demo .现场演示

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

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