[英]I can't understand why break is not working
So I am trying to write a function that checks if there is duplicates inside an array.所以我正在尝试编写一个 function 来检查数组中是否存在重复项。 Once the function detects a duplicate I want it exit break out of the loop and return type.
一旦 function 检测到重复,我希望它退出循环并返回类型。 However in my case it keeps on looping as if the break does not exist.
但是在我的情况下,它会继续循环,就好像中断不存在一样。 Can please someone explain for me why this happening?
有人可以为我解释为什么会这样吗?
public static boolean singleNumber(int[] nums) {
boolean type = false;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j <= nums.length - 1; j++) {
if (nums[i] == nums[j]) {
type = true;
break;
}
}
}
return type;
}
The break
will only get out of the inner loop, not both loops. break
只会退出内部循环,而不是两个循环。 One option is to just return true
instead of break.一种选择是只返回
true
而不是 break。 And return false
at the end of the method if there is no early return.如果没有提前返回,则在方法结束时返回
false
。 No need for the type
variable in this case.在这种情况下不需要
type
变量。
The break
statement has no effect in an if statement. break
语句在 if 语句中无效。 You can only use it for switch, for, while and do
您只能将其用于
switch, for, while and do
In your code the break ends the for loop, not the if.在您的代码中,break 结束了 for 循环,而不是 if。
You could return a boolean instead of a break您可以返回 boolean 而不是休息
your present logic keeps on iterating all the elements even if it finds a duplicate value.即使找到重复值,您当前的逻辑也会继续迭代所有元素。 To change that, you need to check the type value in the outer for loop and if it is true, then you can break from that loop and return the value.
要改变这一点,您需要检查外部 for 循环中的类型值,如果它是真的,那么您可以从该循环中中断并返回该值。
Though your present logic will help in identifying the duplicate values, it will be an overhead once the value is found as it will keep on iterating the array.尽管您当前的逻辑将有助于识别重复值,但一旦找到该值,这将是一种开销,因为它将继续迭代数组。
Here is the solution that should suit your requirement:这是应该适合您要求的解决方案:
public class Main {
public static void main(String[] args) {
System.out.println( singleNumber(new int[]{1,3,1}) );
}
public static boolean singleNumber(int[] nums) {
boolean type = false;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j <= nums.length - 1; j++) {
if (nums[i] == nums[j]) {
type = true;
break; // to break out of the inner for loop
}
}
if( type)
{
break; // to break out of the outer for loop
}
}
return type;
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.