2012-11-08 162 views
1

這裏是我到目前爲止的代碼(當然,while循環):while循環,儘管條件不是循環得到滿足

public class Lab10d 
{ 
public static void main(String args[]) 
{ 
    Scanner keyboard = new Scanner(System.in); 
    char response = 0; 


    //add in a do while loop after you get the basics up and running 

     String player = ""; 

     out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: "); 

     //read in the player value 
     player = keyboard.next(); 

     RockPaperScissors game = new RockPaperScissors(player); 
     game.setPlayers(player); 
     out.println(game); 
    while(response == ('y')) 
    { 
     out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: "); 
     player = keyboard.next(); 
     game.setPlayers(player); 
     //game.determineWinner(); 
     out.println(game); 
     out.println(); 

     // 



    } 
    out.println("would you like to play again? (y/n):: "); 
     String resp = keyboard.next(); 
     response = resp.charAt(0); 
} 
} 

它應該運行代碼的其他次,直到正被輸入

當我輸入唉,它應該重新運行的代碼,但不會

+0

......和你的問題是什麼? – apnorton

+0

您的括號已關閉 – epascarello

+0

並且您有不匹配的括號?我們可以看到完整的代碼嗎? – u8sand

回答

4

您的while循環結束之前,你問他們是否要再次玩。

更改環路:

while(response == ('y')) 
    { 
     out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: "); 
     player = keyboard.next(); 
     game.setPlayers(player); 
     //game.determineWinner(); 
     out.println(game); 
     out.println(); 
     out.println("would you like to play again? (y/n):: "); 
     String resp = keyboard.next(); 
     response = resp.charAt(0); 
    } 

還有一個問題:response循環開始之前沒有被設置爲「Y」。它根本不會在循環中做任何事情。改爲使用do { ... } while (response == 'y')循環。

do 
    { 
     out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: "); 
     player = keyboard.next(); 
     game.setPlayers(player); 
     //game.determineWinner(); 
     out.println(game); 
     out.println(); 
     out.println("would you like to play again? (y/n):: "); 
     String resp = keyboard.next(); 
     response = resp.charAt(0); 
    } while (response == 'y'); 

一個做,而將執行代碼一次然後檢查車況,並繼續執行,如果它是true。 while循環只會檢查條件,並在true時繼續執行。

編輯:我把一些代碼對你:

import java.util.Scanner; 

public class Troubleshoot { 

    public static void main(String[] args) { 
     Scanner s = new Scanner(System.in); 
     char response = ' '; 
     do { 
      System.out.println("Stuff"); 
      System.out.print("Again? (y/n): "); 
      response = s.next().charAt(0); 
     } while (response == 'y'); 
    } 

} 

輸出:

Stuff 
Again? (y/n): y 
Stuff 
Again? (y/n): y 
Stuff 
Again? (y/n): n 
+0

的摘錄,因此他們可能會將y設置爲高於這個值,這不是太重要,更多的問題是循環在他詢問他是否想玩之前結束再次。 (因爲out.println之前的支架) – u8sand

+0

。沒關係。 – Doorknob

+0

看着他的完整代碼,你對沒有設置的響應是正確的,也告訴他在頂部設置'y'的響應,而不是0,或者只是讓它做一個 - 而大聲笑 – u8sand