public class DefaultTest {
private static int next(int i) {
switch(i) {
// 这里加default的理由是什么?而且为什么必须加在这里才行。
default:
case 0: return 0;
case 1: return 1;
}
}
public static void main(String[] args) {
int[] arr = new int[2];
for(int i = 0; i < arr.length; i++) {
arr[i] = next(i);
}
for(int i : arr) {
System.out.println(i);
}
}
}
上述代码如果去掉default编译器会报‘缺少返回语句’的错误。不是很理解,希望有人能够解答,谢谢!switch
private static int next(int i) {
switch(i) {
// 这里加default的理由是什么?而且为什么必须加在这里才行。
default:
case 0: return 0;
case 1: return 1;
}
}
public static void main(String[] args) {
int[] arr = new int[2];
for(int i = 0; i < arr.length; i++) {
arr[i] = next(i);
}
for(int i : arr) {
System.out.println(i);
}
}
}
上述代码如果去掉default编译器会报‘缺少返回语句’的错误。不是很理解,希望有人能够解答,谢谢!switch
不加会报错的原因是因为如果i不是0或1的话,方法就缺少返回值
你可以在switch外面return一个值也行
其实你的default 可以放在最后,然后加一个break就好了 不知道对不对 拙见 献丑了
还有如果我代码改成这样
public class DefaultTest {
private static java.util.Random rand = new java.util.Random(47);
private static int next() {
switch(rand.nextInt(2)) {
default:
case 0: return 0;
case 1: return 1;
// default: 加在这里会报错
}
}
public static void main(String[] args) {
int[] arr = new int[2];
for(int i = 0; i < arr.length; i++) {
arr[i] = next();
}
for(int i : arr) {
System.out.println(i);
}
}
}
这样的话switch中只可能出现0,1两种情况之一,那为什么还要额外加上一条返回语句呢?
还有我试验了下,如果把default放在最后,需要在后面加上return语句,加上break还是会报缺少返回值的错误。
还有如果我代码改成这样
public class DefaultTest {
private static java.util.Random rand = new java.util.Random(47);
private static int next() {
switch(rand.nextInt(2)) {
default:
case 0: return 0;
case 1: return 1;
// default: 加在这里会报错
}
}
public static void main(String[] args) {
int[] arr = new int[2];
for(int i = 0; i < arr.length; i++) {
arr[i] = next();
}
for(int i : arr) {
System.out.println(i);
}
}
}
这样的话switch中只可能出现0,1两种情况之一,那为什么还要额外加上一条返回语句呢?
还有我试验了下,如果把default放在最后,需要在后面加上return语句,加上break还是会报缺少返回值的错误。加上break,当default的时候,你跳出循环,你也没返回值啊。所以会报错。
既然方法有返回值,你就必须让其在所有的情况下返回一个值。否则就会出现错误。
- -。你这么个改法真不知道你在想什么。。好好看看书理解一下switch的执行过程。。
是0,1
即使这么写也不能通过
public int f() {
if(true) {
return 1;
}
}
还是用事实说话,将你的代码生成的class反编译之后,看到next方法变成了这样:private static int next(int i)
{
switch (i) {
case 0:
default:
return 0;
case 1:
}
return 1;
}
编译器认为你那样写的意思是,在i为0或缺省情况下,因为没有break,所以都返回0,在i为1的情况下,虽然退出了switch,但最后还是返回了1.当default方法放在最后的话,0的时候返回0,1的时候返回1,而default,因为return本身起了break的作用,所以default的情况下,就没有返回了,所以程序无法编译。所以default方法在中间也是可以编译的。