如何从该循环的最后一次迭代中获取字符串?
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”并能够用它做一些事情。有任何提示或解决方案如何实现它吗?
最佳答案
您当前的代码已经能够获取最后一次翻转的结果。由于您在循环范围之外声明了变量 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
。
how to propely create newFlip() method to use it your way?
取决于“翻转”的数据类型。如果使用整数表示翻转(例如,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");
}
}
}
关于java - 如何从JAVA中的for循环的最后一次迭代中获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46645768/