我有以下代码用于帮助我找到1和用户输入之间的素数。唯一的问题是,我必须在没有括号和逗号的情况下输出数字。我该怎么做?
System.out.println("\nLab1la\n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the primes upperbond ==>> ");
final int MAX = input.nextInt();
boolean primes[];
primes = new boolean[MAX];
ArrayList<Integer>PrimeFactor = new ArrayList<Integer>();
for (int i = 2; i < MAX + 1 ; i++)
{
PrimeFactor.add(i);
}
CompositeNumbers(PrimeFactor);
System.out.println("COMPUTING RIME NUMBERS");
System.out.println();
System.out.println("PRIMES BETWEEN 1 AND " + MAX);
System.out.print(PrimeFactor);
}
public static void CompositeNumbers(ArrayList<Integer> PrimeFactor)
{
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (!isPrime(PrimeFactor.get(i)))
{
PrimeFactor.remove(i);
i--;
}
}
}
public static boolean isPrime(int n)
{
if(n==1)
{
return true;
}
for (int i = 2; i < n +1/2; i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
}
答案 0 :(得分:1)
依次输出每个值。例如:
// TODO: Rename PrimeFactor to primeFactors to follow Java naming conventions
for (int value : PrimeFactor)
{
System.out.print(value);
System.out.print(" "); // Or whatever separator you want
}
(这将在最后输出一个额外的空间;摆脱它略微繁琐,但不是太难......)
或使用类似Guava的Joiner
类:
System.out.println(Joiner.on(' ').join(PrimeFactor));
答案 1 :(得分:0)
只需使用System.out.print(" ");
即可。我相信它会有所帮助。