我努力了但是我无法让它发挥作用。我的方法"猜测"在课堂上#34;游戏"应该比较参数" someInt"用变量" x"来自班级" Number"。我真的很感激任何帮助,我必须在今晚完成这项工作。到目前为止,这就是我所得到的:
public class Number
{
private int x;
/**
* Constructor for class Number.
* This constructor assigns x to a new random
* number between 1 and 100
*/
public Number()
{
// The following lines creates a random number
// between 1 and 100 and assigns it to x
java.util.Random random = new java.util.Random();
x = random.nextInt(100) + 1;
}
public int getNumber(){
return x;
}
}
我的另一堂课:
public class Game
{
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < x){
System.out.println("Your guess is too small");
}
else if (someInt > x) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}
答案 0 :(得分:1)
这是修改后的版本
public class Game
{
private Number number;
/**
* This constructor should initialize the filled number
*/
public Game() {
this.number = new Number();
}
/**
* This method takes a parameter "someInt" and
* compares it with the value stored in "this.number".
* If "someInt" is less than the value stored in "this.number",
* then the system should print "Your guess is too small" on the screen;
* if "someInt" is larger than that value,
* then the system should print "Your guess is too large" on the screen;
* otherwise it should print "You win!".
*/
public void guess(int someInt) {
if (someInt < number.getNumber()){
System.out.println("Your guess is too small");
}
else if (someInt > number.getNumber()) {
System.out.println("Your guess is too large");
}
else {
System.out.println("You win!");
}
}
}
另一方面,您不应使用与java.lang
中名称相同的类作为Number
。这会分散注意力,使您的代码难以阅读并且具有错误性。
问题是:
Number.getNumber()
没有参数,你提供了一个number1
。number
guess()
中,您使用的是x
,而应使用Number.getNumber()
。我建议将Number
重命名为不会导致java.lang.Number
名称冲突的内容。
答案 1 :(得分:0)
这是错误的:
public Game() {
Number number1 = new Number();
number1.getNumber(x);
}
因为Number.getNumber()
没有参数,必须返回一个int(它是 GETTER )...
也许你打算这样做:
public class Game {
private int x;
private Number number;
/**
* This constructor should initialize the filed number
*/
public Game() {
Number number1 = new Number();
this.x = number1.getNumber();
}
答案 2 :(得分:0)
你有number1.getNumber(x); ,但你的数字类中的getNumber没有参数。
在getNumber方法中,您返回x。你需要在游戏中处理它:
int numberToCompare; (在私人号码下面声明)
number1.getNumber(X);必须是numberToCompare = number1.getNumber();
然后你需要将someint与numberToCompare进行比较。