gpt4 book ai didi

java - 尽管没有使用 boolean 值,但我得到 "Type mismatch cannot convert from int to boolean"

转载 作者:行者123 更新时间:2023-12-02 04:20:19 25 4
gpt4 key购买 nike

我正在《Java 如何编程》一书中做练习。我应该制作一个模拟抛硬币的应用程序。我应该创建一个方法(翻转),它随机返回硬币的一面。我决定让该方法返回 1 或 2,并且在主方法中我将这些值“转换”为硬币的一面。问题是我收到一条错误消息:“类型不匹配 - 无法从 int 转换为 boolean”。我真的认为我一直只使用整数进行操作,看不到 boolean 值是如何进来的。

代码如下:

import java.util.Random;

public class Oppgave629
{

public static void main(String[] args)
{
int command = 1;
int heads = 0;
int tails = 0;
while (command != -1)
{
System.out.print("Press 1 to toss coin, -1 to exit:");
int coinValue = flip();
if (coinValue = 1) {System.out.println("HEADS!"); heads++;}
if (coinValue = 2) {System.out.println("TAILS!"); tails++;}
System.out.printf("Heads: %d", heads); System.out.printf("Tails: %d", tails);
}
}

static int flip()
{
int coinValue;
Random randomValue = new Random();
coinValue = 1 + randomValue.nextInt(2);
return coinValue;
}
}

最佳答案

你的代码

if (coinValue = 1) {System.out.println("HEADS!"); heads++;}
if (coinValue = 2) {System.out.println("TAILS!"); tails++;}

应该是

if (coinValue == 1) {System.out.println("HEADS!"); heads++;}
if (coinValue == 2) {System.out.println("TAILS!"); tails++;}

您将 int 类型分配给 coinValue,并且该类型在 if 语句中被计算为 bool。

关于java - 尽管没有使用 boolean 值,但我得到 "Type mismatch cannot convert from int to boolean",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56640177/

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