-3

我正在制作一个程序,打印出一个数字是否为素数以及它之前的素数,但我有一个问题。我有:

 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.   
       }

    }
}   
    }
4

2 回答 2

0

我不知道你在问什么问题,但这应该做什么?

for (int i = input; i <= input; i--){
        if(isPrimeMethod.isPrime(i) == true){
            primeCounter++;
        }
    }

是什么永远阻止了这种循环?

于 2013-10-29T02:08:14.183 回答
0

好的,所以这段代码有很多可以简化的地方,但这不是这里的问题。

在这种情况下i是数组的索引,而不是素数的实际值。相反,您应该检查:

if(primes[i] != 2)
    System.out.println(primes[i] + ", ");  
else 
    System.out.println(primes[i] + ".");
于 2013-10-29T02:09:51.033 回答