Scanner input = new Scanner(System.in);
System.out.print("First value: ");
int start = Integer.parseInt(input.nextLine());//Gets the first number
System.out.print("Second value: ");
int end = Integer.parseInt(input.nextLine());//Gets the second number
for(int i = start; i <= end; i++){
if(i%2==0){//When the number is divided by 2, it gives a remainder of 0. Modulus helps us get the remainder.
System.out.println(i+" is even");
}else{//Doesn't satisfy the first condition. It must be odd.
System.out.println(i+" is odd");
}
}
我们使用扫描仪读取用户输入,然后使用 for 循环和杠杆模量( % ). 模数计算一个数除以某个数后的余数。如果一个数除以2得到0的余数,这意味着它可以被2整除。我们可以建立一个 if 语句来检查它是否可除。 试运行
First value: 1
Second value: 10
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("1st value: ");
int min = scanner.nextInt();
System.out.print("2nd value: ");
int max = scanner.nextInt();
for (int i = min; i <= max; i++) {
System.out.println(i + " is " + (i % 2 == 0 ? "even" : "odd"));
}
}
}
示例运行:
1st value: 8
2nd value: 15
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
https://www.youtube.com/watch?v=cakn0xc6ccq 使用 number % 2 == 0 对于偶数。
长版本:
// Create a new Scanner() to scan System.in
Scanner scanner = new Scanner(System.in);
// Get the two inputs
int first = scanner.nextInt();
int second = scanner.nextInt();
// Start i as the first number
// While it is less than or equal to the second
// Add one each time
for(int i = first; i <= second; i++) {
// Is there a remainder from dividing i by 2?
// If no, it's even
boolean even = i % 2 == 0;
// Print it
System.out.println(i + " is even: " + even);
}
scanner.close();
4条答案
按热度按时间vmjh9lq91#
你可以这样做:
我们使用扫描仪读取用户输入,然后使用
for
循环和杠杆模量(%
). 模数计算一个数除以某个数后的余数。如果一个数除以2得到0的余数,这意味着它可以被2整除。我们可以建立一个if
语句来检查它是否可除。试运行
cld4siwp2#
你可以用
Scanner
从用户处获取最小和最大范围值。一旦有了这些值,就可以使用一个循环,起始值为最小值,结束值为最大值,步长值为
1
. 在循环中,如果数字可以被2
(即如果数字%2==0),则偶数打印;否则,打印奇数。查看java教程中的for语句,了解有关循环语句的更多信息。
示例运行:
mbjcgjjk3#
简短版本:
https://www.youtube.com/watch?v=cakn0xc6ccq
使用
number % 2 == 0
对于偶数。长版本:
snz8szmq4#
嘿,你可以用for循环,很简单。
我希望你知道如何询问输入,所以把它传递到8和15的位置