【问题标题】:Java rock-paper-scissors program does not print right outputJava石头剪刀布程序不打印正确的输出
【发布时间】:2022-01-24 05:04:42
【问题描述】:

我希望我的程序显示计算机选择的内容。
但相反,它有时不显示,或有时显示

  • The computer chose Rock
  • The computer chose Paper
  • The computer chose Scissors

即使我遵循相同的输入模式也会发生这种情况。

用户按顺序输入 1 , 2 , 3 时输出-

同样,当用户再次按顺序输入 1 , 2 , 3 时输出-

用户随机输入时的输出-

代码-

import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random play= new Random();
        System.out.println("Best of three of Rock paper scissors!");
        int win=0;
        int i =1;
        while(i<=3){
            int number=play.nextInt(3);
            System.out.println("Press 1 for Rock");
            System.out.println("Press 2 for Paper");
            System.out.println("Press 3 for Scissor");
            int ch=scanner.nextInt();
            if(number==1)
                System.out.println("The computer chose Rock");
            if(number==2)
                System.out.println("The computer chose Paper");
            if(number==3)
                System.out.println("The computer chose Scissor");

            if(ch==1 && number==1)
                System.out.println("Draw");
            else if(ch==1 && number==2)
                System.out.println("Lost");
            else if(ch==1 && number==3){
                System.out.println("Won");
                win++;}
            else if(ch==2 && number==1){
                System.out.println("Won");
                win++;}
            else if(ch==2 && number==2)
                System.out.println("Draw");
            else if(ch==2 && number==3)
                System.out.println("Lost");
            else if(ch==3 && number==1)
                System.out.println("Lost");
            else if(ch==3 && number==2){
                System.out.println("Won");
                win++;}
            else if(ch==3 && number==3)
                System.out.println("Draw");

            i++;

        }
        if(win==3 || win==2)
            System.out.println("You won the game!");
        else
            System.out.println("Aww you lost the game.");
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    问题在于int number = play.nextInt(3)。此方法返回 0、1 或 2(文档 here),而您的代码需要 1、2、3。

    一个简单的解决方法是使用int number = play.nextInt(3) + 1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多