java - 如何排除因子程序中的数字?AND 如何在输入某个数字之前重新提示用户?
问题描述
所以我正在做这个项目。我需要
- 编写一个程序,找出整数的因子和因子个数。
- 从最小到最大的因素将列在 1 行中,每个因素之间用空格分隔。
- 不断接受输入,直到输入一个 0,也就是哨兵。不要因数 0。
我得到了保理部分。这是我目前得到的输出。
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 + " ");
}
}
}
}
解决方案
你有一个循环的正确想法 - 你需要循环并检查它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();
}
推荐阅读
- reactjs - 如何在 Web Api 和 React 中为 HttpPOST 方法发布正确的 URL
- julia - 将 Julia 表达式转换为数组?
- xcode - XCUITest:在 Jenkins 上的构建(使用 XCUITests)完成后,如何访问应用程序日志(来自被测应用程序)
- statistics - 考虑马尔可夫过程 (Xn) 时,Xn1-->Xn2-->Xn3 是任意 n1 的马尔可夫链吗
我想获得一些有关马尔可夫链的帮助,因为这真的让我很困惑!如果我们有马尔可夫过程(X_n),下面的陈述总是正确的吗?对于 n1<n2<n3 : Xn1,Xn2,Xn3 是马尔可夫链。
这似乎很简单,但仍然令人困惑。
请帮忙!我只想知道这句话是否总是正确的。谢谢!
- json - 如何从 json 对象的嵌套列表中提取由值标识的列表?
- python - 如何理解这里的 * 参数?
- r - 当我尝试缩放变量时的一些问题
- c++ - 检查是一个单链表是排序迭代方法c ++
- javascript - 从soap xml响应中提取令牌
- tensorflow - Keras ELMO 在训练期间失败:不支持的对象类型 int