如何在java

时间:2015-10-11 03:36:21

标签: java arraylist goto

StartAgain:
    if(nit_arr.size() > 2)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
            goto StartAgain;
        }
    }

如果数组列表中的最后两个元素相同,我想重新生成一个随机数  该列表中包含2个以上的元素。它不是一个使用break / continue的循环。那我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

这是一个可怕的设计决定,但您可以在Java中使用lableled statements。在您的情况下,可能使用

continue StartAgain;

但你真的应该重新设计你的方法。 14.7的JLS链接(部分),

  

与C和C ++不同,Java编程语言没有goto语句;标识符语句标签与标记语句中出现的break§14.15)或continue§14.16)语句一起使用。

答案 1 :(得分:0)

    for(bool again = nit_arr.size() > 2; again;)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
        }
        else{
             again = false;
             // do other stuff if needed
        }
    }

这就是我们如何实现它,以及大多数其他结构,而不需要goto语句。通常不推荐在C / C ++中使用Goto,因为它会破坏代码的结构并使其更难以跟踪(由人工)。当然,编译版本中的所有内容都将被翻译成gotos,jumps等。

使用休息的另一种方式;建议稍微少一些,但确定​​:

    while(nit_arr.size() > 2)
    {
        System.out.println("size of list is more than 2");
        j = prev.size()-2; 
        k = prev.size()-3; 
        if(nit_arr.get(j) == myChoice && nit_arr.get(k) == myChoice){
            //System.out.println("Last 2 selections of nitish are same so next one should not be");
            myChoice = (int )(Math.random() * 2);
        }
        else break;
    }