【问题标题】:Trying to gain a better grasp of loop logic.试图更好地掌握循环逻辑。
【发布时间】:2013-10-21 05:22:39
【问题描述】:

我希望你的星期天一切顺利。所以我在这个小程序中的目标是打印一个索引为 [0,1] [4,5]...[12,13]... 的新字符串...循环仅适用于大于 4 个字母的偶数单词.为什么是这样?任何关于如何抛光这个粪便的建议将不胜感激。谢谢。

import java.util.Scanner;

public class LoopPractice {
public static void main(String[] args) {

  Scanner myScanner = new Scanner(System.in);

  System.out.print("Enter a String please: ");
  String str = myScanner.next();

  int count = 0;
  int x = 0;
  int y = 1;
  String emptyStr = "";

     while ( count != str.length() ) {

        emptyStr += str.charAt(x) + "" +  str.charAt(y);
        x += 4;
        y += 4;
        count += emptyStr.length();
     }
  System.out.print(emptyStr);

}
}

【问题讨论】:

  • 其实我所在的地方是星期一,这种思维方式会给你的编程带来很多问题
  • 你得到了什么操作?
  • “小猫”这个词 --> kien
  • 和“CodingConnor”这个词 --> Congnn
  • 我强烈建议不要调用变量emptyStr,除非它总是为空的。看到底部System.out.print(emptyStr); 的人会想知道为什么要打印空字符串,但事实上,您不是。

标签: java while-loop charat


【解决方案1】:

我不是 100% 确定您的问题,但问题似乎出在此处:x += 4; y += 4;。您每次将这两个变量增加 4(X 为 0、4、8,Y 为 1、5、9)。

当您使用.charAt 函数时,您很可能会收到一个错误,表明存在一些越界问题,因为 X 和 Y 的值大于字符串的长度。

您需要更改 X 和 Y 的递增方式才能停止出现该错误。

【讨论】:

  • @Carlitolos 另外,正如其他人指出的那样,您可能想看看您的while 条件。
【解决方案2】:

while 条件下,应该检查是否没有溢出字符串索引:

import java.util.Scanner;

public class LoopPractice {
public static void main(String[] args) {

  Scanner myScanner = new Scanner(System.in);

  System.out.print("Enter a String please: ");
  String str = myScanner.next();

  int x = 0;
  int y = 1;
  String emptyStr = "";

     while ( y <= str.length() ) {

        emptyStr += str.charAt(x) + "" +  str.charAt(y);
        x += 4;
        y += 4;
     }
  System.out.print(emptyStr);

}
}

【讨论】:

    【解决方案3】:

    这就是你所需要的:

    System.out.print("Enter a String please: ");
    String str = myScanner.next();
    while(!str.isEmpty()){
              System.out.println(str.charAt(0)+""+str.charAt(1));
              if(str.length()>4)
                  str = str.substring(4);
              else
                  str = "";
         }
    

    【讨论】:

      【解决方案4】:

      问题出在这一行

      count += emptyStr.length();
      

      您的emptyStr 每次都会变长两个字符。所以第一次通过时,您将 2 添加到 count。下一次,您添加 4,然后添加 6,依此类推。所以count 取值 0、2、6、12、20 等等。

      如果str.length() 不是这些值之一,您的循环将永远不会结束。

      【讨论】:

        猜你喜欢
        • 2021-10-09
        • 2017-01-09
        • 1970-01-01
        • 2019-11-06
        • 2011-05-29
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多