首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

3个小疑点

2012-03-13 
3个小问题Java code//当break z 返回到z的时候,会不会再次开始循环?public void go(){String o z:for

3个小问题

Java code
//当break z 返回到z的时候,会不会再次开始循环?public void go(){     String o = "";         z:         for(int x=0; x<3; x++){             for(int y=0; y<2; y++){                             if(x == 1) break;                             if(x==2 && y==1) break z;                             o = o + x + y;             }         }     System.out.println(o); } //5是怎么来的?public class Test {    public static void main(String[] args) {        String[] colors = { "blue", "red", "green", "yellow", "orange" };        Arrays.sort(colors);        int s2 = Arrays.binarySearch(colors, "orange");        int s3 = Arrays.binarySearch(colors, "violet");        System.out.print(s2 + "" + s3);    }}//为什么编译失败?public class Test {    public static void main(String[] args) {        new Test.go("hi", 1);        new Test.go("hi", "world", 2);    }    public void go(String... y, int x) {        System.out.print(y[y.length - 1] + " ");    }}


[解决办法]
第一题:z标识的就是外层for循环,break z即直接跳出外层循环,当然不会从头开始执行这两个嵌套for循环。
第二题:你调用的是Arrays.sort(Object[] a,Object key),看API说明如下:
如果它包含在数组中,则返回搜索键的索引;否则返回 (-(插入点) - 1)。插入点 被定义为将键插入数组的那一点:即第一个大于此键的元素索引,如果数组中的所有元素都小于指定的键,则为 a.length。注意,这保证了当且仅当此键被找到时,返回的值将 >= 0。 
你排序String[]是按首字母>次字母……的自然顺序将colors排序为:blue、green、orange、red、yellow。violet的插入点位yellow之后,可以由api说明得知,返回(-4)-1,即-5.第二题打印输出应为2-5。
第三题给你一个正确的程序,自己对照看错误在哪里:
Java code
public class Test {    public static void main(String[] args) {        new Test().go(1,"hi" );        new Test().go(2,"hi", "world" );    }    public void go(int x,String... y) {        System.out.print(y[y.length - 1] + " ");    }} 

热点排行