2015-10-16 207 views
-3

我正在为学校进行作业,我无法通过playerTurn方法,因为do while部分不会为我编译。这就是我写:If/else语句和while while循环

public class Pig { 
    public static void main (String[] args){ 
     Random generator = new Random(); 
     Scanner console = new Scanner(System.in); 
     int roll = diceRoll(generator); 
     System.out.println("You rolled a " + roll); 


} 
public static int diceRoll(Random generator){ 
    int num = generator.nextInt(6) + 1; 
    return num; 
} 
public static int playerTurn(java.util.Scanner input, java.util.Random rand){ 
    int turnScore = 0; 
    int roll; 
    String response; 

    do { 
     roll = diceRoll(generator); 
     System.out.println("You rolled a " + roll); 

     if (roll == 1) { 
      turnScore = 0; 
      System.out.println("Oh no! You rolled a 1 which means your turn is over and your score is 0"); 
      return turnScore; 
     } else { 
      System.out.println("Do you want to roll again? Yes or No"); 
      response = console.next(); 
     } while (response.equalsIgnoreCase("Yes")) { 
      return turnScore; 
     } 
    } 
} 

}

的编译错误我不断收到有:

Pig.java:35:错误:预期 } ^

Pig.java:37:错误:表达式的非法开始 } ^

Pig.java:37:错误:文件的最终达成在分析 } ^

Pig.java:40:错误:文件的最终达成在分析

4个错误

我很确定我所有的括号都匹配,但如果不是这样,我不知道如何解决它。提前致谢。

+0

你的大括号是错的。 while条件在关闭之后}在第30行关闭第30行的''''else'''语句。 – Siddhartha

+0

'do/while'语句不应该有括号。 。'while(condition);'就像这样一段时间 – 3kings

+0

另外,你的'''返回turnScore;''在第31行错误的地方,你不能把它放在while语句中,你需要把它放在方法的末尾, – Siddhartha

回答

0

这里将编译为雅。

import java.util.Random; 
import java.util.Scanner; 

public class Pig 
{ 
    public static void main (String[] args) 
    { 
    Random generator = new Random(); 
    Scanner console = new Scanner(System.in); 
    int roll = diceRoll(generator); 
    System.out.println("You rolled a " + roll); 

    } 
    public static int diceRoll(Random generator) 
    { 
    int num = generator.nextInt(6) + 1; 
    return num; 
    } 

    public static int playerTurn(java.util.Scanner input, java.util.Random rand) 
    { 
     int turnScore = 0; 
     int roll; 
     String response; 

     do 
     { 
      roll = diceRoll(rand); 
      System.out.println("You rolled a " + roll); 

      if (roll == 1) 
      { 
       turnScore = 0; 
       System.out.println("Oh no! You rolled a 1 which means your turn is over and your score is 0"); 
       return turnScore; 
      } 
      else 
      { 
       System.out.println("Do you want to roll again? Yes or No"); 
       response = input.next(); 
      } 
     }while (response.equalsIgnoreCase("Yes")); 
    return turnScore; 
} 
} 
+2

请将'while'放在与end-brace相同的行上,否则它看起来像是一个空的body的新while循环。 – Andreas