2013-12-07 18 views
-3

我想用java代码切换到相同的execute?我怎么能做到这一点由java我想用if-else替换java代码来切换

if(ave>=90.0) 
    return 'A'; 
else if(ave>=80.0) 
    return 'B'; 
else if(ave>=70.0) 
    return 'C'; 
else if(ave>=60.0) 
    return 'D'; 
else 
    return 'F'; 
+2

神奇。写一些代码。 –

+1

资本D是ascii 68,所以你可以做strVar =(Math.max(Math.min(68-(90-ave)/ 10,65)),68).toString();但可能不适用于单个字符,也许只有字符串 –

+0

缺乏'E'故意? – Pshemo

回答

2

直观的解决方案是:这是不可能的。

交换机需要一组谨慎的元素。号范围是无限的,你不能做

switch(something) { 
case 90.0: 
case 90.000000000001: 
.... 

有一个办法,你可以做到这一点,虽然:转换至一些数字:

private static int toRangeIndex(double d) { 
    if (d >= 90.0) 
     return 0; 
    else if (d >= 80.0) 
     return 1; 
    else if (d >= 70.0) 
     return 2; 
    else if (d >= 60.0) 
     return 3; 
    else 
     return 4; 
} 

public static double sumColoumn(double[][] m, int coloumnIndex) { 
    switch (toRangeIndex(ave)) { 
    case 0: 
     return 'A'; 
    case 2: 
     return 'B'; 
    case 3: 
     return 'C'; 
    case 4: 
     return 'D'; 
    default: 
     return 'F'; 
    } 
} 

这显然是在没有更好的你案件。但有些情况下你可以使用这种技术。

+0

看来,OP正试图避免if()else if()..',而不是用单独的方法包装它。 – Pshemo

+0

@Pshemo我知道。我不会这样做,因为它只是更多的代码。但是如果你有一个保持内部状态为'double'的对象,那么添加这样一个方法是个好主意,这样代码就可以使用一个简单的'switch'。转换代码只存在一次,使用转换值的代码可以存在多次。 – zapl

2

不可能直接,switch需要完全匹配。

你可以做的是写功能,如:

int classify(double avg) { 
    // perform some if-else chain, or loop with test inside, or calculation: 
    return (int)(avg/10.0); 
} 

然后在开关使用返回值:

switch (classify (avg)) { 
case 10: // average of exact 100.0 gives 10, let's not F that... 
case 9: 
    return 'A'; 
case 8: 
    return 'B'; 
//... 
default: 
    return 'F'; 
} 

但是,在特定情况下,它只是移动如果...梯子变成不同的功能,并且可能不是个好主意。所以不要这样做:-)。

或者说,如果你这样做,这样做,因为它使代码更易于理解和维护(在这里它在我看来没有),而不是因为你要使用switch声明。

0
int findIndex(double ave){ 
int index=(int)(ave/10.0); 
if(index>=9) 
    return 9; 
else 
    return index; 

}

switch (findIndex(ave)) { 
    case 9: 
     return 'A'; 
    case 8: 
     return 'B'; 
    case 7: 
     return 'C'; 
    case 6: 
     return 'D'; 
    default: 
     return 'F'; 
} 
0

我瑶池回答

switch(t1) 
    { 
    case 100: case 99: case 98: case 97:case 96:case 95:case 94:case 93:case 92:case 91:case 90: 
    cr='A'; 
    break; 
    case 89: case 88: case 87: case 86:case 85:case 84:case 83:case 82:case 81:case 80: 
    cr='B'; 
    break; 
    case 79: case 78: case 77: case 76:case 75:case 74:case 73:case 72:case 71:case 70: 
    cr='C'; 
    break; 
    case 69: case 68: case 67: case 66:case 65:case 64:case 63:case 62:case 61:case 60: 
    cr='D'; 
    break; 
    default: 
    cr = 'F'; 
    break;  
    }