这是我所拥有的(这只是我整个代码的摘录):
int num = (int) Math.random()*100;
switch(num)
{
case 0 : compChoice = "R";break;
case 1 : compChoice = "P";break;
case 2 : compChoice = "S";break;
}
我怎样才能让它只产生一个随机数 0、1 或 2?
在我稍后的返回声明中,它说这里获取的字母导致“空”
如果有帮助,这是整个代码:
import java.util.Scanner;
import static java.lang.System.*;
public class RockPaperScissors
{
private String playChoice;
private String compChoice;
public RockPaperScissors()
{
}
public RockPaperScissors(String player)
{
playChoice = player;
}
public void setPlayers(String player)
{
playChoice = player;
int num = (int) Math.random()*100 %3;
switch(num)
{
case 0 : compChoice = "R";break;
case 1 : compChoice = "P";break;
case 2 : compChoice = "S";break;
}
out.print(compChoice);
}
public String determineWinner()
{
String winner="";
if(playChoice == "R")
{
switch(compChoice)
{
case "R" : winner = "!Draw Game!";break;
case "P" : winner = "!Computer wins <<Paper Covers Rock>>!";break;
case "S" : winner = "!Player wins <<Rock Breaks Scissors>>!";break;
}
}
else if(playChoice == "P")
{
switch(compChoice)
{
case "R" : winner = "!Player wins <<Paper Covers Rock>>!";break;
case "P" : winner = "!Draw Game!";break;
case "S" : winner = "!Computer wins <<Scissors Cuts Paper>>!";break;
}
}
else if(playChoice == "S")
{
switch(compChoice)
{
case "R" : winner = "!Computer wins <<Rock Breaks Scissors>>!";break;
case "P" : winner = "!Player wins <<Scissors Cuts Paper>>!";break;
case "S" : winner = "!Draw Game!";break;
}
}
return winner;
}
public String toString()
{
String output="";
output = "player had " + playChoice + "\n computer had " + compChoice + "\n " + determineWinner();
return output;
}
}
这是我的跑步者课程,因为有人指出我没有在任何地方调用任何方法:
import java.util.Scanner;
import static java.lang.System.*;
public class Lab10d
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
char response;
//add in a do while loop after you get the basics up and running
String player = "";
out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: ");
//read in the player value
player = keyboard.next();
RockPaperScissors game = new RockPaperScissors(player);
game.determineWinner();
out.println(game);
while(response == response)
{
out.print("Rock-Paper-Scissors - pick your weapon [R,P,S] :: ");
player = keyboard.next();
game.setPlayers(player);
game.determineWinner();
out.println(game + "\n");
out.println("would you like to play again? (y/n):: ");
response = (char) keyboard.next();
}
}
}