奇怪的是“如果!=”Java错误

时间:2013-10-29 01:59:54

标签: java

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

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

    }
}   
    }

2 个答案:

答案 0 :(得分:0)

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

for (int i = input; i <= input; i--){
        if(isPrimeMethod.isPrime(i) == true){
            primeCounter++;
        }
    }
是什么让这个循环永远停止了?

答案 1 :(得分:0)

好的,所以在这段代码中可以简化很多,但这不是问题所在。

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

if(primes[i] != 2)
    System.out.println(primes[i] + ", ");  
else 
    System.out.println(primes[i] + ".");