首页 > 解决方案 > 如何排除因子程序中的数字?AND 如何在输入某个数字之前重新提示用户?

问题描述

所以我正在做这个项目。我需要

我得到了保理部分。这是我目前得到的输出。

Enter an Number
12
The factors are 
1 2 3 4 6 12 

它在给出因素后立即停止。我不确定如何实现它以重新提示。我试过循环,但它不起作用。另外,如何排除 1 和输入的数字。

这就是我的输出的样子。一旦输入 0,它应该停止。

Enter a number: 12
There are 4 factors for the number 12: 2 3 4 6
Enter a number: 25
There are 1 factors for the number 25: 5
Enter a number: 100
There are 7 factors for the number 100: 2 4 5 10 20 25 50
Enter a number: 13
There are 0 factors for the number 13:
Enter a number: 0

这是代码。

package com.FactorsProgram;
import jdk.swing.interop.SwingInterOpUtils;
import java.sql.SQLOutput;
import java.util.Scanner;


 //Java Program to print all factors of a number using function

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

        System.out.println("Enter an Number");
        N = scanner.nextInt();

        // Calling printFactors method to print all
        // factors of N
        printFactors(N);
    }


     //This method prints all factors of N
    public static void printFactors(int N) {
        int i;

         //Check for every number between 1 to N, whether it divides N. If K
         //divides N, it means K is a factor of N
        
        System.out.println("factors for the number " );
        for (i = 1; i <= N; i++) {
            
            if (N % i == 0) {

                System.out.print(i + " ");
            }
        }
    }
}

标签: java

解决方案


你有一个循环的正确想法 - 你需要循环并检查它n不是0. 例如:

System.out.println("Enter an Number");
n = scanner.nextInt();
while (n != 0) {
    // Calling printFactors method to print all
    // factors of N
    printFactors(n);

    System.out.println("Enter an Number");
    n = scanner.nextInt();
}

推荐阅读