繁体   English   中英

如何从JAVA中的for循环的最后一次迭代中获取字符串?

[英]How to get a string from the last iteration from for-loop in JAVA?

我如何从此循环的上一次迭代中获取字符串?

    public void Flip()
    {
        for (int i = 1; i <= numberOfFlips; i++ )
        {
            System.out.println("Flip " + i + ": " + headOrTail);
            i++;
            System.out.println("Flip " + i + ": " + headOrTail2);
        }

    }

numberOfFlips = 2的输出是:

翻转1:头

翻转2:尾巴

等等。

我的目的是从上次迭代结果中获取“ headOrTail”,并能够对其进行处理。 任何提示或解决方案如何达到目的?

只是问问它是否是las循环。

public void Flip()
    {
        for (int i = 1; i <= numberOfFlips; i++ )
        {
            System.out.println("Flip " + i + ": " + headOrTail);
            i++;
            System.out.println("Flip " + i + ": " + headOrTail2);
            if(i==numberOfFlips){
                <do what you want here>
            }
        }

    }

您当前的代码已经能够获取上一次翻转的结果。 由于您在循环范围之外声明了变量headOrTail ,因此只需更新每个翻转,就可以在循环之后进行打印。

for (int i = 1; i <= numberOfFlips; i++ )
{
    headOrTail = newFlip();    //update your new flip
    System.out.println("Flip " + i + ": " + headOrTail);
}

System.out.println("My last flip: " + headOrTail );

注意:由于您没有更新headOrTail当前代码将始终输出相同的翻转结果。

如何适当地创建newFlip()方法以您的方式使用它?

取决于“翻转”的数据类型。 如果使用整数表示翻转(例如,0表示头部,1表示尾部),则创建一种方法以返回0-1的随机数。

//One of the possibilities..
public static int newFlip(){
    Random rnd = new Random();
    return rnd.nextInt(2);    //you can use Math.random() as well
}

如果所有内容都包含在一个类中,则可以按以下方式进行操作:

//Example..
class CoinTosser
{
    private static Random rnd = new Random();
    private int currentFlip;  //this is also your last flip

    public void newFlip(){
        currentFlip = rnd.nextInt(2);  //in this case, no need to return toss result
    }

    public void flipCoin(int times){
        for(int i=0, i<times; i++){
            newFlip();
            System.out.println("Attemp "+ (i+1) + ":" + currentFlip==0?"Head":"Tail");
        }
    }
}

在循环之前初始化Stringboolean ,然后在每个循环中覆盖它,最后的结果将保留在其中。 或者只是使用if语句保存它,如某人所建议的那样检查它是否是最后一个循环。

这是你想要的?

public void Flip()
{
    String lastInteraction = null;
    for (int i = 1; i <= numberOfFlips; i++ )
    {
        System.out.println("Flip " + i + ": " + (lastInteraction = ((i % 2) == 0 ? "Head" : "Tail"));
        if(lastInteraction.equals("Head")) {
            System.out.println("Last flip was head");
        } else {
            System.out.println("Last flip was tail");
        }
    }

}

这将存储并打印最后的结果; 头或尾

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM