我正在尝试完成一个hackerrank算法挑战,它将在一系列交替的天气模式之后预测树的高度。我不知道为什么我的逻辑不起作用。Java说我的switch语句中的断点不起作用。我已经完整地粘贴了下面的代码。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt(); // user input how many test cases
System.out.println("test cases set.");
int[] cycles = new int[i];
for (int x = 0; x < i; x++) {
cycles[x] = scan.nextInt(); // user input test cycles
}
for (int x = 0; x < i; x++) {
System.out.println(cycles[x]);
int temp = predictor(cycles[x]);
System.out.println(temp);
}
}
public static int predictor(int cycles) {
// determines the remainder to find even or odd cycle year
int heightRemainder = cycles % 2;
switch (heightRemainder) {
case 0:
System.out.println("Even number");
return cycles; // UNREACHABLE, cycles is a temp variable to check functionality
break;
case 1:
System.out.println("Odd number");
return cycles; // UNREACHABLE, same here
break;
}
return -1;
}
}发布于 2016-12-03 15:11:50
是的,它不会工作,因为你的break语句在return语句之后,执行控制不会转到break语句。
在切换情况下不是返回,而是使用变量来存储循环值,然后在方法结束时返回该变量,如下所示
public static int predictor(int cycles) {
// determines the remainder to find even or odd cycle year
int heightRemainder = cycles % 2;
int r=-1;
switch (heightRemainder) {
case 0:
System.out.println("Even number");
r =cycles;
break;
case 1:
System.out.println("Odd number");
r=cycles
break;
}
return r;
}
}发布于 2016-12-03 15:43:41
在predictor方法中:删除break;语句...这是死代码,因为您返回的是循环值
switch (heightRemainder) {
case 0:
System.out.println("Even number");
return cycles; // UNREACHABLE, cycles is a temp variable to check functionality
case 1:
System.out.println("Odd number");
return cycles; // UNREACHABLE, same here
}https://stackoverflow.com/questions/40945178
复制相似问题