【问题标题】:Perfect Number Method w/ Range带范围的完美数法
【发布时间】:2015-10-23 10:49:50
【问题描述】:

我无法显示“它不是一个完美的数字”。我需要最后一部分的帮助。它不允许我将其更改为 else。

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;
                }
            }
        }
    }
}

【问题讨论】:

  • 你需要学习如何正确缩进和格式化代码
  • “我在最后一部分需要帮助。它不允许我将其更改为其他部分。”你这是什么意思?
  • 我需要把它改成 if - else if (sum != n1) { System.out.println("" + starval + " 和 " + endval 之间没有完美数);休息;

标签: java for-loop range perfect-numbers


【解决方案1】:

除非有另一个 if 语句,否则不能在 if 语句中放置 else 语句。

这是整个代码。此外,您没有阅读所有输入的数字。第一个 for 循环应该是 n1

    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");
    }
}

【讨论】:

  • 谢谢。所以我尝试了它,但它保持没有数字。输入起始值:1 输入终止值:100 1到100之间没有完美数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多