简体   繁体   English

对这个循环中的括号感到困惑

[英]Confused about the brackets in this loop

This is the question in Coding bat(the Java version):: Given an array of ints, return true if the array contains a 2 next to a 2 somewhere. 这是Coding bat(Java版本)中的问题:: 给定一个int数组,如果数组在某个地方包含2,则返回true。 has22({1, 2, 2}) → true has22({1, 2, 1, 2}) → false has22({2, 1, 2}) → false has22({1,2,2})→true has22({1,2,1,2})→false has22({2,1,2})→false

This was my solution: 这是我的解决方案:

public boolean has22(int[] nums) {

  for (int i=0; i<nums.length-1;i++) {

     if (nums[i]==2 && nums[i+1]==2) {
         return true;
     }
     else {

        return false;
     } 
  }
}

Doesn't compile while this does.. 这样做时不编译..

public boolean has22(int[] nums) {

  for (int i=0; i<nums.length-1;i++) {

     if (nums[i]==2 && nums[i+1]==2) {
         return true;
     }
     else {

     } 
  }    
    return false;

}

Sorry if this is a stupid question but I'm confused about the brackets at the end. 对不起,如果这是一个愚蠢的问题,但我对最后的括号感到困惑。

Imagine a case when your argument is empty or null . 想象一下你的参数为空或为null Your first method doesn't compile, because it doesn't return a boolean value for all cases. 您的第一个方法无法编译,因为它不会为所有情况返回boolean值。

Your second method compiles, because it will return a boolean value in any case, after the iteration is complete. 你的第二个方法编译,因为在迭代完成后它会在任何情况下返回一个boolean值。

  public boolean has22(int[] nums) 
     {
      for (int i=0; i<nums.length-1;i++) 
       if (nums[i]==2 && nums[i+1]==2) 
         return true;  
       return false;
     }

You can write your program like above no need of braces. 您可以像上面一样编写程序,不需要大括号。 for each conditional statement one statement is always there if we want to associate more than one statement with any conditional statement then we provide {} braces for example if(some condition) 对于每个条件语句,如果我们想要将多个语句与任何条件语句相关联,则一个语句始终存在,然后我们提供{}大括号,例如if(某些条件)
stmt1; stmt1; no need of braces but if more than one statement then if(some condition) { stmt1; 不需要大括号,但如果不止一个语句那么(某些条件){stmt1; stmt2; stmt2; } }

so always remember more than one statement braces compulsory and to avoid problem when ever open a bracket just close at the same time and write inside that one it will let you some relax. 所以永远记住不止一个语句必须强制并避免问题,因为只要在同一时间关闭时打开一个括号并在其中写入它会让你放松一下。 Thanks asif aftab 谢谢asif aftab

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

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