簡體   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