我收到“类型不匹配无法从int转换为boolean"的信息.尽管没有使用布尔值 [英] I get "Type mismatch cannot convert from int to boolean" despite not using boolean

查看:103
本文介绍了我收到“类型不匹配无法从int转换为boolean"的信息.尽管没有使用布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在"Java如何编程"一书中做练习.我应该做一个模拟投币的应用程序.我应该做一个方法(翻转),该方法随机返回硬币的一面.我倾向于使该方法返回1或2,在主方法中,我将值转换"为代币一侧.问题是我收到一条错误消息,内容为:类型不匹配-无法从int转换为boolean".我真的认为我一直都只使用整数,并且不知道布尔值是怎么来的.

I am doing an excercise in the book "Java how to program". I am supposed to make an application that simulates coin-tossing. I am supposed to make a method (flip) which returns randomly a side for the coin. I have desided to make the method return either 1 or 2, and in the main-method I "convert" the values to mean one of the sides of the coin. The problem is that I get an error message that says: "Type mismatch -cannot convert from int to boolean". I really think that I am operating only with integers all the way, and canot see how the booleans come in.

代码如下:

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++;}

您正在为intValue分配一个int类型,并且该类型在if语句中被作为布尔值进行评估.

You're assigning an int type to coinValue and that is being evaluated as a bool inside the if statement.

这篇关于我收到“类型不匹配无法从int转换为boolean"的信息.尽管没有使用布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆