一个关于剪刀石头纸游戏的Java代码 [英] A Java code about scissor-rock-paper game

查看:29
本文介绍了一个关于剪刀石头纸游戏的Java代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经学习了 1 个月的 Java.我对我的代码有疑问.有问题.如果我按0,结果只有计算机赢"和平局"两种情况.所以当我按 1 和 2 时,它只出现了两个.这里有什么问题?

I’ve learned Java for 1 month. I have a question about my code. There is something wrong.If I press 0, the outcomes only has "Computer win" and "Tie" two situation. So as I press 1 and 2, it only comes out two. What's wrong in here ?

import java.util.Scanner;
public class Hm3 {
public static void main (String[] args) {
    int Computer=0,Player=0,tie=0,compic=0,pscore=0;tie=0;
    int end = 0;
    Scanner scan = new Scanner(System.in);
    while (end < 3) {
        System.out.print("Enter 0 for Scissors, 1 for Rock, and 2 for Paper : ");
        pscore = scan.nextInt();
        compic = (int)(Math.random()*2);

        switch (pscore){            
        case 0 :
            if (compic == 0){
                System.out.println("Tie");
                tie++;
            }else if (compic == 1){
                System.out.println("Computer Win");
                Computer++;
            }else{
                System.out.println("Player Win");
                Player++;
                end++;
            }
            break;
        case 1 :
            if (compic == 0){
                System.out.println("Player Win");
                Player++;
                end++;
            }else if (compic == 1){
                System.out.println("Tie");
                tie++;
            }else{
                System.out.println("Computer Win");
                Computer++;
            }break;
        case 2 :
            if (compic == 0){
                System.out.println("Computer Win");
                Computer++;
            }else if (compic == 1){
                System.out.println("Player Win");
                Player++;
                end++;
            }else{
                System.out.println("Tie");
                tie++;
            }break;
        default :               
            System.out.println("The wrong value");              
            break;
        }      
  }
    System.out.println("");
    System.out.println("The player wins : " + Player);
    System.out.println("The computer wins : " + Computer);
    System.out.println("Tie : " + tie);
 }
}

推荐答案

是的,我也认为问题在于您的随机数生成.在处理整数时,我更喜欢使用这种方法,因为不涉及舍入或强制转换:

Yes I also believe that the problem is with your random number generation. When dealing with integers I prefer to use this method because there is no rounding or casting involved:

Random random = new Random(); //create a random object

random.nextInt(3); //will return a random integer from 0 to 2

nextInt() 方法括号中的数字是范围,如果你想从 1 到 3 就改成

The number in the parenthesis of the nextInt() method is the range if you want to go from 1 to 3 just alter it to

random.nextInt(3) + 1;

这篇关于一个关于剪刀石头纸游戏的Java代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆