0

「完全な数ではありません」を表示できません。最後の部分で助けが必要です。他のものに変更することはできません。

package editmess;

import java.util.Scanner;

public class Editmess {

    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("\nPerfect Number Finder Program");

        System.out.print("\nEnter the start value: ");
        int starval = scanner.nextInt();
        System.out.print("Enter the end value:");
        int endval = scanner.nextInt();

        for (int n1 = starval; n1 < endval; n1++) {
            int sum = 0;
            for (int n2 = 1; n2 < n1; n2++) {
                if (n1 % n2 == 0) {
                    sum = sum + n2;
                }
            }

            if (sum == n1) {
                System.out.println(n1 + " is a perfect number");
                if (sum != n1) {
                    System.out.println("There is no perfect number between " + starval + " and " + endval);
                    break;
                }
            }
        }
    }
}
4

1 に答える 1

0

別の if ステートメントがない限り、else ステートメントを if ステートメント内に配置することはできません。

これがコード全体です。また、入力されたすべての数値を読み取っていませんでした。最初の for ループは n1 <= endval でなければなりません。n1 < endval ではありません。入力されたenvalもチェックするようにします。

    Scanner scanner = new Scanner(System.in);
    int counter = 0;

    System.out.println("\nPerfect Number Finder Program");

    System.out.print("\nEnter the start value: ");
    int starval = scanner.nextInt();
    System.out.print("Enter the end value:");
    int endval = scanner.nextInt();

    for (int n1 = starval; n1 <= endval; n1++) {
        int sum = 0;
        for (int n2 = 1; n2 < n1; n2++) {
            if (n1 % n2 == 0) {
                sum = sum + n2;
            }
        }

        if (sum == n1) {
            System.out.println(n1 + " is a perfect number");
             counter ++; //This will add one to the counter if this loop is enterd
            }
         if(n1 == endval){
            System.out.println("FINISHED!");
            break;
         }
    }
    //If the counter is 0 then it will display the message
    if(counter == 0){
        System.out.println("THERE IS NO PERFECT NUMBERS");
    }
}
于 2015-10-23T01:35:46.100 に答える