不能将Int转换为布尔值吗?将代码从C转换为Java [英] Int cannot be converted to boolean?? converting code from C to Java

查看:136
本文介绍了不能将Int转换为布尔值吗?将代码从C转换为Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要转换为Java的代码,这是我的编程新手,但是我已经在两个PL上都做了一些工作,尽管我不明白为什么会收到此错误

I have a code that I am converting into Java, Im new to programming but I already have done some work on both PL, although I do not understand why I get this error

原始的C代码是:

#include <stdio.h>
#include <conio.h>

int main () {
    int i, j, k;
    for (i=1; i<=59; i++) {
        k = 1;
        for (j=2; j<i; j++)
            if (i % (j*j) == 0) k = 0;
        if (k) printf ("%d\n", i);
    }
    printf("%d",i);
    getch();
}

我转换后的Java代码:

My converted Java code:

import java.util.*;
public class squarefree {

    public static void main(String[] args) {
        int i, j,k;
        for(i=1; i<60; i++){
            k=1;
            for(j=2; j<i; j++){
                if(i % (j*j) == 0) 
                    k=0;
                if(k) System.out.println(i);
            }
            System.out.println(i);
        }
    }
}

有人可以解释吗?谢谢大家:)

Can someone please explain? Thanks guys :)

推荐答案

2种解决方法:

1)使用if (k != 0),因为在Java中,intint,而boolean是它自己的类型.

1) Use if (k != 0), since in java an int is an int and a boolean is its own type.

2)话虽如此,为什么不将k更改为布尔值呢?您正在使用它进行布尔检查,并且它仅从0变为1,因此,如果您实际使用布尔值,它将更容易阅读.

2) Having said that, why not change k to a boolean value? You're using it for a boolean check, and it only changes from 0 to 1, so if you actually use the boolean value it'll be much easier to read.

例如:

boolean k = true;

// your code here
    // your ifstatement to change k
    k = false;

// print code
if (k) ...

这篇关于不能将Int转换为布尔值吗?将代码从C转换为Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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