簡體   English   中英

Java中的While / Do While循環

[英]While/ Do While loops in Java

這是我的問題:

一名學生決定慶祝感恩節的開始,盡早搗碎,以慶祝這一點。

她的家在大街上的0號角,監獄在大街上的10號角。 學生從第5個角開始,向左或向右一個角徘徊,每個概率為0.5; 她重復此過程,直到安全到達家中或入獄為止。 也就是說,在每個角落,醉酒的學生有50-50的概率左右搖擺到下一個較高編號的角落或下一個較低編號的角落。

使用一個while或do-while循環編寫一個名為drunkWalk()的方法來模擬醉酒的學生的行走; 您的方法應該返回一個整數,該整數既表明已執行了多少步驟,又表明學生是入獄還是在家。 如果返回的步數為負數(如果此人落入監獄),則返回為正數;如果返回的步數為正數(如果該人最終在家中),則可以執行此操作。 盡管您可能希望在調試時執行此操作,但是您不應打印出該方法的最終版本中執行的每個步驟。

一旦方法生效,請讓主程序對drunkWalk()方法調用N次(其中N是最終變量)。 最后,讓它計算並打印出學生一次旅行的平均步數。 N等於5時,您的程序的運行情況如下所示:

Here we go again... time for a walk! <br/>
Took 37 steps, and <br/>
Landed at HOME<br/>

Here we go again... time for a walk!<br/>    
Took 19 steps, and <br/>
Landed in JAIL<br/>

Here we go again... time for a walk!<br/>
Took 13 steps, and <br/>
Landed in JAIL<br/>

Here we go again... time for a walk! <br/>
Took 25 steps, and <br/>
Landed in JAIL<br/>

Here we go again... time for a walk!<br/>
Took 15 steps, and <br/>
Landed at HOME<br/>

Average # of steps equals 25.4<br/>

這是我的代碼:它可以編譯,但是沒有輸出。 我認為我的代碼過於復雜,但是我不知道如何簡化它:

class Drunk     
{

// When this code runs, nothing prints out????

  public static void main(String[] args)
  {
    int home = 0; 
    int jail = 10;  

    final int N = 5; 
    int sum = 0;

    int a = drunkWalk(N); 
    sum = sum + a; 

    //System.out.println ("Average # of steps equals" + " " + (a/sum));

  }

  static int drunkWalk(int x)
  {
    int steps; // steps is the number of steps taken by the student
    int total=5;  // total is the starting point of the student (at corner 5)

    while (x > 0); 
    {   
      do 
      { 
        steps = (int) (Math.random() * (10 +  10) - 10); 
        total += steps;
        x = x-1;
      } while (total != 0 || total != 10);
    }

    if (total == 0) 
    {
      System.out.println("Here we go again... time for a walk!");
      System.out.println("Took" + " " + steps + "steps, and");
      System.out.println ("Landed at HOME"); 
    }

    if (total == 10) 
    { 
      System.out.println("Here we go again... time for a walk!");
      System.out.println("Took" + " " + steps + "steps, and");
      System.out.println ("Landed in JAIL"); 
    }

    return steps; // Need to figure out how to add up ALL the steps
  }

請幫忙!

; after while終止您的循環。 因此,刪除分號; 在while語句之后:

while (x > 0);// remove semicolon  ;

當您的第一個while循環終止時,值totalsteps不會改變。

嘿,您的代碼有一個INFINITE循環

do { 
    steps = (int) (Math.random() * (10 +  10) - 10); 
    total += steps;
    x = x-1;
} while (total != 0 || total != 10);

在這里,假設您的total = 0然后total != 10得到滿足,因此循環將繼續進行;如果您的total = 10然后total != 0再次得到滿足,則循環繼續“您已使用||運算符” 您應該這樣使用&&

    do { 
       steps = (int) (Math.random() * (10 +  10) - 10); 
       total += steps;
       x = x-1;
    } while (total != 0 && total != 10);

注意:根據需要考慮循環邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM