不能将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中,int
是int
,而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) ...