English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

System.out.print("Enter your play (R, P, S): ");
personPlay=Keyboard.readString();

//Use a method of the String class to make the personPlay all UPPERCASE
personPlay.toUpperCase();

//Use Math.random() to generate computer's play as either 0, 1 or 2
//Store result in computerInt
computerInt=(int)Math.random()*3;
//Use else-if to convert 0, 1 or 2 to initialize computerPlay to R, P or S
if(computerInt==0)
computerPlay="R";
else
{ if(computerInt==1)
computerPlay="P";

if(computerInt==2)
computerPlay="S";
}

System.out.println("The computer played: " + computerPlay);

/*-------------------------------------------------------
every time i compile and run the program, it always outputs "The computer played: R" ....so there is something wrong with my if-else statements, but i can't figure out what?

2007-12-09 10:36:21 · 5 answers · asked by hahahahahaha 1 in Computers & Internet Programming & Design

Believe it or not-- I have studied java code and understand how Math.random works....

2007-12-09 11:44:56 · update #1

5 answers

I just see som bad syntax... I'm a little rusty, but shouldn't it read:

if(computerInt==0) {
computerPlay="R";
}
if(computerInt==1){
computerPlay="P";
}
if(computerInt==2){
computerPlay="S";
}

Plus the randomization string should probably be:

computerInt=Math.floor (Math.random()*2) ;

2007-12-09 11:17:47 · answer #1 · answered by DimensionalStryder 4 · 0 0

Math.random() returns numbers between 0 and 1. you should have a multiplier first, say 100. if you want the generated values limited to a certain number, use the modulo operator.
for example, you want a number to be a maximum of 2 only, you may write:
computerInt = ((Math.random())*100)%2;

2007-12-09 19:43:19 · answer #2 · answered by momoy 2 · 0 0

The cast is binding more tightly than the multiplication. I think you want computerInt=(int)(Math.random()*3);

2007-12-09 18:51:49 · answer #3 · answered by daa 7 · 0 0

I think your problem is in your use of Math.random().....if I'm not mistaken it should be variable = (int)(3*Math.random); but your way might work too, I've always put parentheses around the scaler multiplication.

2007-12-09 18:45:40 · answer #4 · answered by Anonymous · 1 0

daa has it right. The logic is weird, but should work.

2007-12-09 20:08:29 · answer #5 · answered by Whatever 3 · 0 0

fedest.com, questions and answers