gpt4 book ai didi

java - 我尝试运行这段代码,它运行时不会抛出错误,问题是它不会执行 for 循环我只是一个初学者,所以请

转载 作者:行者123 更新时间:2023-12-02 08:55:38 25 4
gpt4 key购买 nike

求 2 和输入值之间所有偶数的和?

import java.util.Scanner;

public static void main(String[] args) {
//initialization and declaration of variable
int input, sum = 0;
Scanner sc = new Scanner(System.in);

//Ask user to input data
System.out.print("Enter a number you want to limit up-to : ");
input = sc.nextInt();

//Conditions
if(input < 2) {
System.out.println("Error Occurred! Please, Enter a number greater or equal to 2. ");
}

for (int i = 2; i <= input; i++ ) {
if( i % 2 == 0) {
sum += i;
}
}
}

最佳答案

您应该打印结果sum。在 main 方法关闭之前添加 System.out.println("the sum is:"+ sum) 。完整代码如下:

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//initialization and declaration of variable
int input, sum = 0;
Scanner sc = new Scanner(System.in);

//Ask user to input data
System.out.print("Enter a number you want to limit up-to : ");
input = sc.nextInt();

//Conditions
if(input < 2) {
System.out.println("Error Occurred! Please, Enter a number greater or equal to 2. ");
}

for (int i = 2; i <= input; i++) {
if( i % 2 == 0) {
sum += i;
}
}
System.out.println("the sum is:" + sum);
}
}

作为Tim-Hunter也就是说,你可以将i的步长设置为2。因为如果i是偶数,则i+1一定是奇数。代码如下:

for (int i = 2; i <= input; i+=2) {
if( i % 2 == 0) {
sum += i;
}
}

关于java - 我尝试运行这段代码,它运行时不会抛出错误,问题是它不会执行 for 循环我只是一个初学者,所以请,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60509300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com