【问题标题】:My code won't return anything! output is simply blank我的代码不会返回任何东西!输出只是空白
【发布时间】:2013-10-13 03:40:21
【问题描述】:

我正在用 java 编写此代码来扫描数字或字母字符串以查看它们是否是连续的。一切似乎都运行良好,直到我尝试在其中放置一个布尔值以返回 true 或 false,但什么也没发生!我错过了什么?谢谢! :)

这里是:

public class Question1 {
  public static void main(String[]args){
    String s = "gFeD";
    isConsecutive(s);
  }
    public static boolean isConsecutive(String s){
      boolean letters;
      letters = false;
      int counter = 0;
      String newS = s.toLowerCase();
      for (int i = 0; i < newS.length() - 1; i++){
        if (newS.charAt(i) - newS.charAt(i+1) == 1){
          return true;
      } else if (newS.charAt(i) - newS.charAt(i+1) == -1) {
        return true;
      }
     }
      return letters;
    }
   }

【问题讨论】:

  • "I'm writing this code in java to scan numerical or alphabetical strings to see if they are consecutive. Everything seems to be working fine until I try to place a boolean in there to return true or false but nothing is happening! What am I missing?"——也许是你的代码。您没有发布任何代码!
  • 如果您想将任何内容打印到控制台,请使用System.out.println。如果您不使用它,请不要期望控制台中有任何内容 =\
  • 请注意,您可以将if 条件简化为:if(Math.abs(newS.charAt(i) - newS.charAt(i+1)) == 1) return true;

标签: java boolean stdio


【解决方案1】:
  for (int i = 0; i < newS.length() - 1; i++){
    if (newS.charAt(i) - newS.charAt(i+1) == 1){
      return true;
  } else if (newS.charAt(i) - newS.charAt(i+1) == -1) {
    return true;
  }

这不是你想要的。

  • 您不希望在 in for 循环中返回 true。除非您发现订单未得到维护,否则不会。否则你会回来太早。另一方面,如果您发现订单实际上是关闭的,则返回 false 是可以的。
  • 您不想检查 char - otherchar == 1 还是 -1,因为这太严格了。您想查看 > 0 或

【讨论】:

  • +1 以更批判性地看待处理过程,而不仅仅是 OP 所询问的内容
【解决方案2】:

你没有对返回值做任何事情。如果您想在控制台上看到它,请执行System.out.println(isConsecutive(s));。这就是为什么“什么都没有发生”。在您编写它时它运行正常;它只是不会产生任何可见的输出。

【讨论】:

    【解决方案3】:

    只需将 main 方法的最后一行替换为 System.out.println(isConsecutive(s));。这应该有效。

    【讨论】:

      【解决方案4】:

      你没有打印任何东西,试试System.out.println(isConsecutive(s));

      【讨论】:

        猜你喜欢
        • 2015-04-15
        • 1970-01-01
        • 1970-01-01
        • 2017-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多