2012-11-08 120 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