我正在运行此代码,但我无法访问main方法中的类变量(pg和dg)。我得到的输出是
经销商正在开始游戏 他猜到了一个从0到9的数字 现在是时候猜测了 玩家正在猜测 猜测的玩家1是0 玩家正在猜测 猜测的玩家2是0
玩家正在猜测 猜测的数字玩家3是0
经销商的猜测是0
所有人都猜对了
我无法捕获方法中生成的随机数。
class player
{
public int pg = 0;
public void pguess()
{
System.out.println("Player is guessing");
int pg = (int)(Math.random() * 10);
}
}
class dealer
{
public int dg = 0;
public void guess()
{
System.out.println("Dealer is starting the game");
System.out.println("He has guessed a number from 0 to 9");
System.out.println("Now it is your time to guess");
int dg = (int)(Math.random() * 10);
}
public void dealerdisplay()
{
System.out.println("The dealer guess was " + dg);
}
}
public class gameOn
{
public static void main(String args[])
{
dealer d = new dealer();
player a = new player();
player b = new player();
player c = new player();
d.guess();
a.pguess();
System.out.println("The number player 1 guessed is " + a.pg);
b.pguess();
System.out.println("The number player 2 guessed is " + b.pg);
c.pguess();
System.out.println("The number player 3 guessed is " + c.pg);
d.dealerdisplay();
if ((d.dg == a.pg) && (d.dg == b.pg) && (d.dg == c.pg))
System.out.println("All have guessed correctly");
else if ((d.dg == a.pg) && (d.dg == b.pg) || (d.dg == a.pg) &&
(d.dg == c.pg) || (d.dg == b.pg) && (d.dg == c.pg))
System.out.println("Two have have guessed correctly");
else if ((d.dg == a.pg) || (d.dg == b.pg) || (d.dg == c.pg))
System.out.println("One has guessed correctly");
else
System.out.println("No one has guessed correctly");
}
}
答案 0 :(得分:5)
这是你的问题:
System.out.println("Player is guessing");
int pg = (int)(Math.random()*10);
}
您正在声明新的本地int pg而不是设置类成员。改为:
System.out.println("Player is guessing");
pg = (int)(Math.random()*10);
}
看看它是否有效。
答案 1 :(得分:0)
变量dg和pg都是在guess()内部创建的。 默认情况下,java将值0赋给int类型,因此每次打印它的值时,都会将其设置为零。
你需要在guess方法中的赋值语句中删除int。
System.out.println("Player is guessing");
pg = (int)(Math.random()*10);
System.out.println("He has guessed a number from 0 to 9");
System.out.println("Now it is your time to guess");
dg = (int) (Math.random() * 10);