java - Java 中的 For 循环

标签 java loops

所以我正在创建一个简单的剪刀石头布,最近我犯了一个错误。我刚刚开始学习,我犯了一个错误并且不知道错误在哪里。我真的非常感谢任何指出我犯错误的地方的指示。当它打印出提示时,我输入我想要的内容,它就会再次打印出来。谢谢!

import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class rock_Paper_Scissor {
    public static void main (String[] args) {
        String playerhand;
        boolean x =  true;
        Scanner input = new Scanner(System.in);
        Random num = new Random();
        int rand = num.nextInt(2) + 1;
        System.out.println("I challenge you to Rock Paper Scissor");
        System.out.println("If you want to quit, type exit twice");
        System.out.println("Type Rock, Paper, or scissor");
        playerhand = input.nextLine();
        String hands = playerhand.toLowerCase();
        while (x == true) {
            if (hands == "rock") {              
                if (rand == 1) {
                    System.out.println("Rock vs. Rock: TIE");
                } else if (rand == 2) {
                    System.out.println("Rock vs. Scissor: YOU WIN");
                } else if (rand == 3) {
                    System.out.println("Rock vs. Paper: YOU LOSE");
                }
            } 
            else if (hands == "paper") {
                if (rand == 1) {
                    System.out.println("Paper vs. Rock: YOU WIN");
                } else if (rand == 2) {
                    System.out.println("Paper vs. Scissor: YOU LOSE");
                } else if (rand == 3) {
                    System.out.println("Paper vs. Paper: TIE");
                }
            } 
            else if (hands == "scissor") {
                if (rand == 1) {
                    System.out.println("Scissor vs. Rock: YOU LOSE");
                } else if (rand == 2) {
                    System.out.println("Scissor vs. Scissor: TIE");
                } else if (rand == 3) {
                    System.out.println("Scissor vs. Paper: YOU WIN");
                }
            }
            else if (hands == "exit") {
                System.out.println("Thank you for playing!");
                x = false;
            }
            System.out.println("Please type your hand to play again: ");
            hands = input.nextLine();
        }
    }
}

最佳答案

在所有 if 条件中尝试使用 eqauls() 方法而不是 == ,如下所示:

  if ("rock".equals(hands)) { 
   ...
   else if ("paper".equals(hands)) {
   ...     
    else if ("scissor".equals(hands )) {
       ...
    else if ("exit".equals(hands)) {

.equals() 用于比较字符串值。 但 == 与引用字符串进行比较。

关于java - Java 中的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356134/

相关文章:

java - Windows 8.1 上的磁带机目录路径

java - JSON 解析过滤逗号分隔的记录

java - 在 JAVA 中格式化 Date.toString() 输出

c - 程序在函数循环后停止

Python 跳转 while 循环

java - 如何使用 x、y 坐标列表绘制曲线(峰)

Java 将 Int 转换为 Hex 并将其粘贴到字节数组元素中

Java整数数学从0-4连续循环

php - WooCommerce 产品自定义循环由一系列 SKU 过滤

python - 双循环中增加服务器数量,每 5 个服务器带有分隔符