设计一个Java程序,完成: 将所有的十进制表示的三位整数中找出其平方数中有连续的三位数字就是该数本身的数。 如:250的平方数是62500,其5位数字中包含250在内。因此:250就是一个要找出的三位。 将结果写入文本文件result.txt中,格式为:第一列是该数 第二列是该数的平方。 100 10000 250 62500 xxx xxxxxx
时间: 2024-04-01 12:37:54 浏览: 12
好的,以下是Java程序的实现:
```java
import java.io.*;
public class SquareNumber {
public static void main(String[] args) {
try {
// 打开文本文件准备写入结果
BufferedWriter writer = new BufferedWriter(new FileWriter("result.txt"));
// 遍历所有的三位整数
for (int i = 100; i <= 999; i++) {
int square = i * i;
String squareStr = String.valueOf(square);
// 判断平方数中是否包含该数本身
if (squareStr.contains(String.valueOf(i))) {
// 判断平方数中是否包含连续的三位数字
for (int j = 0; j <= squareStr.length() - 3; j++) {
String subStr = squareStr.substring(j, j + 3);
if (subStr.equals(String.valueOf(i))) {
// 输出结果到文件
writer.write(i + "\t" + square + "\n");
break;
}
}
}
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
程序的核心就是遍历所有的三位整数,计算其平方数并判断是否满足要求。其中,判断平方数中是否包含该数本身使用了String类的contains()方法;判断平方数中是否包含连续的三位数字则使用了String类的substring()方法。
最后,将程序保存为SquareNumber.java文件,然后在命令行中编译并运行代码即可。
相关推荐
![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)