我正在制作一个程序,打印出一个数字是否为素数以及它之前的素数,但我有一个问题。我有:
if(i != 2){ System.out.println(primes[i] + ", "); else System.out.println(primes[i] + ".");
如果数字为 2,则应显示“2”。但是它会放置一个以 3 结尾的任何数字的句点,有什么问题吗?:P 这是我的代码
package me.Jesse.PrimeCalc;
import java.util.Scanner;
public class PrimeArrayCalculator {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int primeCounter = 0;
int arrayCounter = 0;
int[] primes;
int input;
System.out.println("Please Enter A Number.");
input = scan.nextInt();
System.out.println("Calculating Results... (This may take a while!) ");
System.out.println("");
if(isPrimeMethod.isPrime(input) == true){
System.out.println(input + " Is Prime!");
System.out.println("Calculating The Prime Numbers Before " + input + "...");
System.out.println("");
}else{
System.out.println(input + " Is Not Prime.");
System.out.println("Calculating The Prime Numbers Before " + input + "...");
System.out.println("");
}
for (int i = input; i <= input; i--){
if(isPrimeMethod.isPrime(i) == true){
primeCounter++;
}
}
primes = new int[primeCounter++];
for (int i = input; i <= input; i--){
if(isPrimeMethod.isPrime(i) == true){
primes[arrayCounter] = i;
arrayCounter++;
}
}
System.out.println("Here Are All The Prime Numbers Before " + input + ":");
System.out.println("");
for (int i = 0; i <= primeCounter; i++){
try{
if (primeCounter != 2)
System.out.println(primes[i] + ",");
else
System.out.println(primes[i] + ".");
}catch(ArrayIndexOutOfBoundsException e){
// Yes I know the program trys to print from two invalid array index's. Try/Catch FTW.
}
}
}
}