打印奇数java
时间: 2023-09-28 11:05:40 浏览: 53
可以使用 for 循环和 if 语句来打印奇数:
```java
for (int i = 1; i <= 100; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
}
```
这段代码会打印出 1 到 100 之间的所有奇数。
相关问题
java打印奇数
以下是Java语言中打印奇数的代码示例:
```java
public class PrintOddNumbers {
public static void main(String[] args) {
int n = 10; // 打印1-10之间的奇数
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) { // 使用取余运算判断是否为奇数
System.out.println(i);
}
}
}
}
```
上述代码中,使用了for循环遍历1到n之间的所有数字,然后使用if语句判断该数字是否为奇数,如果是,则使用System.out.println()方法打印出来。需要注意的是,判断一个数字是否为奇数,可以使用取余运算符%来判断,如果一个数字对2取余等于1,则表示该数字是奇数。
多线程输出奇数Java
以下是一个Java多线程程序,用于输出奇数:
```
public class OddNumberPrinter implements Runnable {
private int maxNumber;
public OddNumberPrinter(int maxNumber) {
this.maxNumber = maxNumber;
}
@Override
public void run() {
for (int i = 1; i <= maxNumber; i += 2) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
public static void main(String[] args) {
OddNumberPrinter oddNumberPrinter = new OddNumberPrinter(10);
Thread thread1 = new Thread(oddNumberPrinter, "Thread 1");
Thread thread2 = new Thread(oddNumberPrinter, "Thread 2");
thread1.start();
thread2.start();
}
}
```
在这个程序中,我们创建了一个名为OddNumberPrinter的类,实现了Runnable接口。在run()方法中,我们使用for循环打印从1到maxNumber的所有奇数。在main()方法中,我们创建了两个线程并启动它们。两个线程将会同时运行,并输出1到10之间的所有奇数。
相关推荐
![](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)