gpt4 book ai didi

java - 类型不兼容的问题

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

我是 Java 和学习新手 - 所以请原谅这可能是一个愚蠢的问题!

这是一个简单的剪刀布游戏...

使用 BlueJ 我不断收到此错误;

“不兼容的类型”

运行此代码时;

import comp102.*; 

import java.util.Scanner;


public class RPS{

String paper = "paper";
String rock = "rock";
String scissors = "scissors";

public void playRound(){

String paper = "paper";
String rock = "rock";
String scissors = "scissors";

System.out.print ('\f'); // clears screen
Scanner currentUserSelection = new Scanner(System.in);

String enterText = null;
System.out.println("Make your Selection; Paper, Rock or Scissors: ");
enterText = currentUserSelection.next();

System.out.println("enterText = " + enterText);

if(enterText = paper){
System.out.println("the IF Stmt is working");
}

}

错误指的是这一行“if(enterText = paper){”

非常感谢

最佳答案

您正在尝试在 if 中赋值,这是不允许的

if(enterText = paper)  //here if expects expression which evaluates to boolean  

更改为,

if(enterText == paper)

来自language specs jls-14.9

The if statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.

The Expression must have type boolean or Boolean, or a compile-time error occurs.

不要使用 == 运算符,而是使用 String#equals比较字符串。

if(enterText.equals(paper))  //this will compare the String values  

另请参阅

关于java - 类型不兼容的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19627972/

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