在Java 中,int i = (int)true什么意思
时间: 2023-12-26 14:06:46 浏览: 68
在Java中,布尔类型不能直接转换成整型,因此编译器会报错。需要使用条件运算符或if语句进行转换,例如:
```
int i = true ? 1 : 0;
```
或者
```
int i;
if (true) {
i = 1;
} else {
i = 0;
}
```
这样可以将布尔类型的true转换成整型1,将布尔类型的false转换成整型0。
相关问题
java中 int比较用==还是equals
在Java中,对于基本数据类型`int`,比较通常使用`==`,因为`==`比较的是两个数值是否相等。
而对于对象类型的`Integer`,比较应该使用`equals()`方法,因为`Integer`是一个类,使用`==`比较的是两个对象在内存中的地址是否相同,而不是它们所包含的数值是否相等。
举个例子,如果有如下代码:
```
int a = 5;
int b = 5;
Integer c = new Integer(5);
Integer d = new Integer(5);
```
那么`a==b`的结果是`true`,因为`a`和`b`都是基本数据类型,比较的是它们的数值是否相等。
而`c==d`的结果是`false`,因为`c`和`d`是两个不同的对象,它们在内存中的地址不同。
但是`c.equals(d)`的结果是`true`,因为`equals()`方法比较的是两个`Integer`对象所包含的数值是否相等,而不是它们在内存中的地址是否相同。
综上所述,对于基本数据类型`int`,使用`==`进行比较即可,而对于对象类型的`Integer`,应该使用`equals()`方法进行比较。
把这段代码翻译成java语言(源语言为c++)#include <iostream> #include <cmath> using namespace std; bool isPerfectSquare(int num) { for(int i = 1; i * i <= num; i++) { if(i * i == num) { return true; } } return false; } int main() { int num = 0; for(int i = 1000; i <= 9999; i++) { int t = 0; int p = i; while(p != 0) { int x= p % 10; t = t * 10 + x; p /= 10; } if(isPerfectSquare(abs(t - i))) { num++; } } cout << num; return 0; }
以下是将C++代码翻译成Java的代码:
import java.lang.Math;
public class Main {
public static boolean isPerfectSquare(int num) {
for(int i = 1; i * i <= num; i++) {
if(i * i == num) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int num = 0;
for(int i = 1000; i <= 9999; i++) {
int t = 0;
int p = i;
while(p != 0) {
int x = p % 10;
t = t * 10 + x;
p /= 10;
}
if(isPerfectSquare(Math.abs(t - i))) {
num++;
}
}
System.out.println(num);
}
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)