gpt4 book ai didi

java - 嵌套 if - else 语句的问题

转载 作者:行者123 更新时间:2023-12-01 09:26:24 26 4
gpt4 key购买 nike

我对编码非常陌生,并尝试根据我在这里看到的代码编写一个石头剪刀布代码。然而,当系统应该在打印计算机所玩的内容后输出游戏结果时,它只是不打印。有任何想法吗?谢谢!

import java.util.Scanner;
import java.util.Random;

public class Rock {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);
Random gen = new Random();

System.out.println("Hey, let's play Rock, Paper, Scissors!\n" +
"Please enter a move.\n" + "Rock = R, Paper" +
"= P, and Scissors = S.");

int computerInt = gen.nextInt(3)+1;

String computerPlay = "";
if (computerInt == 1)
computerPlay = "R";
else if (computerInt == 2)
computerPlay = "P";
else if (computerInt == 3)
computerPlay = "P";

System.out.print("Please enter your play: ");

String personPlay = scan.next();
personPlay = personPlay.toUpperCase();
System.out.println("Computer play is: " + computerPlay);

if (personPlay.equals(computerPlay))
System.out.println("It's a tie!");
else if (personPlay.equals("R"))
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
else if (personPlay.equals("P"))
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
else if (personPlay.equals("S"))
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
else
System.out.println("Invalid user input.");
}
}

最佳答案

您的 if 语句的嵌套是完全错误的。你的缩进(几乎)暗示了你希望如何执行你的代码,但是编译器根本不关心你的缩进,它只遵守java语言的规则。

if() else if() if() 这样的多个嵌套条件语句很难(由人类)确定它们将如何执行。

所以:永远不要使用多个不带花括号的语句。 (有些人甚至说始终使用花括号,即使只有一个语句。)

当存在哪怕是最轻微的歧义时(就像您编写的代码中存在的那样),请确保始终添加花括号,以确保编译器将按照您想要的方式编译您的代码。

然后,您的代码(可能)就会工作。

关于java - 嵌套 if - else 语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com