gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:56 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++;}

您正在为 coinValue 分配一个 int 类型,并且它在 if 语句中被评估为 bool。

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

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