2013-12-09 44 views
4

我正在从一本书学习到用java代码。它给出了猜谜游戏的例子并给出了代码。我想保留它作为参考。但我不断收到错误。这可能是我输入它的方式,因为我正在阅读它,它有点乱了。不是一个声明

有很多像这样的错误,但没有人喜欢我的。我试图做一个猜谜游戏,但我不断收到此错误:

GuessingGame.java:17:不是语句 (int)(Math.random()* 10)+ 1;

代码:

import java.util.Scanner; 
public class GuessingGame 
{ 
    static Scanner sc = new 
Scanner(System.in); 
    public static void 
main(String[] args) 
    { 
    bolean keepPlaying = true; 
    System.out.println("Let's play a guessing game!"); 
    while (keepplaying) 
    { 
     bolean validInput; 
     int number, guess; 
     String answer; 
     // Pick a random number = 
    (int)(Math.random() * 10) + 1; 
     // Get the guess 
     System.out.print("What do you think it is? "); 
     do 
     { 
      guess = sc.nextInt(); 
      validInput = true; 
      if ((guess < 1) || (guess > 10)) 
      { 
       System.out.print 
        ("I said between 1 and 10. " 
        + "Try again: "); 
       validInput = false; 
      } 
     }while (!validInput); 
     // Check the guess 
     if (guess == number) 
      System.out.println(
     "You're right!"); 
     else 
      System.out.println(
     "You're wrong! " + "The number was " + number); 
     // Play again? 
     do 
     { 
      System.out.println("\nPlay again? (Yes or No)"); 
      answer = sc.next(); 
      validInput = true; 
      if (asnwer.equalsIgnoreCase("Yes")); 
      else if (answer.egualsIgnoreCase("No")- 
       keepPlaying = false); 
      else 
         validInput = false; 
     } while (!validInput); 
    } 
    System.out.println("\nThank you for playing!"); 
} 

}

+0

哟认为'(int)(Math.random()* 10)+ 1;'应该这样做吗?你为什么这么想? –

+0

你对表达式'(int)(Math.random()* 10)+ 1'做了什么? – rgettman

+1

你正在做一个数学运算和对该操作的投射......然后从不将任何结果赋值给一个变量,所以结果只是......“挂起”在那里...... –

回答

6

这是真的,(int)(Math.random() * 10) + 1;不是一个声明。与其他一些语言不同,Java不允许表达式作为语句。

我认为这个词number在评论上述属于上线:

不:

// Pick a random number = 
(int)(Math.random() * 10) + 1; 

但是:

// Pick a random number 
number = (int)(Math.random() * 10) + 1; 

(有已经高于int number;,所以变量已经宣布了,而且都是。)

1

你h一个number变量被引用,但从未创建。我假设这是需要采取正确数字的变量。更改:

(int)(Math.random() * 10) + 1; 

number = (int)(Math.random() * 10) + 1; 
+0

@Quirliom:是的,但是我评论的hexa答案的版本是重新声明它的。他从此撤消了重新宣布。 –

1

这是因为(int)(Math.random() * 10) + 1;只是得到一个随机数作为int但不会存储为任何东西。尝试这样做。

number = (int)(Math.random() * 10) + 1; 
2

您需要将您在声明中计算的值赋予变量。 在你的情况下,它是可变数字。

number = (int)(Math.random() * 10) + 1;