我用java制作了一个保理程序。我有一个带有2个包的eclipse项目。一个人只有一个班级,我遇到问题,另一个班子里面什么都没有。 当我点击运行时,没有任何反应,我不明白为什么。
这是java代码:
package com.frostbytedev.factor;
import java.util.ArrayList;
import java.util.Scanner;
public class factor {
static ArrayList<Integer> notFactors = new ArrayList<Integer>();
static ArrayList<Integer> factors = new ArrayList<Integer>();
static int i = 0;
/**
* @param args
*/
public static void main(String[] args){
// TODO Auto-generated method stub
Initialize();
}
private static void Initialize() {
// TODO Auto-generated method stub
System.out.println("Enter a number to factor below:");
Scanner in = new Scanner(System.in);
int number = in.nextInt();
FactorNumber(number);
PrintList(Factors);
}
private static void PrintList(ArrayList<Integer> factorsToPrint) {
// TODO Auto-generated method stub
for(i=0;i<factorsToPrint.size()-1;i++){
System.out.print(factorsToPrint.get(i)+", ");
}
System.out.print(factorsToPrint.size());
}
private static void FactorNumber(int number) {
// TODO Auto-generated method stub
for(i=2;i<number/2;i++){
if(number%i==0){
FactorNumber(i);
FactorNumber(number/i);
} else {
notFactors.add(i);
}
}
if(notFactors.size()==number){
factors.add(number);
}
};
}
答案 0 :(得分:1)
尝试通过右键单击Project Explorer中的类文件来运行您的类 - &gt;运行方式... - &gt; Java应用程序
答案 1 :(得分:0)
代码中存在以下错误 1)由于我是静态的,你的代码中存在无限循环。 2)因素应该是一套避免重复的 3)if(notFactors.size()== number / 2 - 1)as循环以2开头。 4)for(int i = 2; i&lt; = number / 2; i ++)它应该是&lt; =
这不会打印1&amp;数字本身也是因素。如果您需要它们,可以添加到集合中。
package com.frostbytedev.factor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class Test {
static ArrayList<Integer> notFactors = new ArrayList<Integer>();
static Set<Integer> factors = new HashSet<Integer>();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Initialize();
}
private static void Initialize() {
// TODO Auto-generated method stub
System.out.println("Enter a number to factor below:");
Scanner in = new Scanner(System.in);
int number = Integer.parseInt(in.nextLine());
in.close();
FactorNumber(number);
PrintList(factors);
}
static void PrintList(Set<Integer> factorsToPrint) {
// TODO Auto-generated method stub
for (int factor : factorsToPrint) {
System.out.print(factor + ", ");
}
System.out.println(factorsToPrint.size());
}
private static void FactorNumber(int number) {
// TODO Auto-generated method stub
for (int i = 2; i <= number / 2; i++) {
System.out.println(i);
if (number % i == 0) {
factors.add(i);
FactorNumber(i);
FactorNumber(number / i);
} else {
notFactors.add(i);
}
}
if (notFactors.size() == number / 2 - 1) {
factors.add(number);
}
};
}