私は、0からユーザーが入力した数値までの偶数の合計を出力するプログラムを作成しています。たとえば、ユーザーが20番を入力した場合、プログラムは0と20の間のすべての偶数の合計を計算します。偶数の整数のJavaプログラムの無限ループ
数字10のプログラムをテストしたところ、しかし、私は別の番号、35を使用してみました、そして、それはちょうど無限ループで立ち往生していました。私は何かすべての助けに感謝します。コードは以下に掲載されます:
(編集)フィードバックありがとうございました!友人と話をした後、私たちは解決策が実際にはとても簡単だと気付きました。私たちはただそれを複雑にしていました。それでも、すべての提案に感謝します。
//**************************************************************
// Prints the sum of the even numbers within a range of 0
// and the integer that the user enters.
//
// @me
// @version_1.0_11.7.17
//**************************************************************
import java.util.Scanner;
public class EvenNumbersSum
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int user_num = 2; // variable that stores the user's number
int sum; // stores the sum of the needed values
System.out.print("Enter an integer greater than or equal to, 2: "); // prompt user for input
user_num = input.nextInt();
// checks to see if the value entered is valid or not.
while (user_num < 2)
{
System.out.println("Invalid entry. Must enter an integer greater than or equal to, 2.\n");
System.out.print("Enter an integer greater than or equal to, 2: ");
user_num = input.nextInt();
}
// starts adding the values
for (sum = 0; sum <= user_num;)
{
if (user_num % 2 == 0) // checks if the number is even
sum+=user_num; // add the number to sum
else
continue; // I thought that I might need this, but ended up changing nothing.
}
System.out.println(); // extra line for cleanliness
System.out.printf("The sum of the even numbers between 0 and %d is %d.", user_num, sum); // prints the result
}
}
user_numはforループ内で変更されません。もう一度入力を受け入れる必要があります。 –
forループ内の 'sum'と' user_num'を2項で比較しているのはなぜですか? – John3136
'for(sum = 0; sum <= user_num;)'は意味をなさないので、 'user_num'回ループしませんか?その数値を合計するかどうかを決定するためにその値を使用します。 – MadProgrammer