2016-12-10 113 views
0

我被要求用顯示1st 100 Palindromic素數的方法編寫一個java程序。我需要顯示每行10個數字。每個號碼佔6個地方。我完成了整個程序,但我被困在每個數字如何佔用6個我不知道這樣做的地方。那麼我怎樣才能讓每個號碼佔據6個地方呢?如何顯示每行10個數字。每個號碼佔6個地方。

public class PalindromicPrime { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    final int NUMBER_OF_PALINPRIME = 100; 
    int numberPrinted = 0, testedNumber = 2; 

while (numberPrinted < NUMBER_OF_PALINPRIME) { 
    if (isPrime(testedNumber) && isPalindrome(testedNumber)) { 
     numberPrinted++; 
     System.out.print(testedNumber + " "); 
    if (numberPrinted % 10 == 0) { 
     System.out.println(); 
}//end of 2nd if 
} //end of 1st if 
testedNumber++; 



}// end while 




} // main method 




/** Check whether number is prime */ 
public static boolean isPrime(int number) { 
    for (int divisor = 2; divisor <= number/2; divisor++) { 
    if (number % divisor == 0) { // If true, number is not prime 
    return false; // number is not a prime 
    } // end if 
    } // end for loop 



    return true; // number is prime 
} // end isPrime method 
public static int reverse(int number) { 


int reverse = 0; 
    int digit; 

    do { 
    digit = number % 10; 
    reverse = reverse * 10 + digit; 
    number /= 10; 
    } // end do; 
    while (number != 0); 

    return reverse; 
} // end reverse method 

public static boolean isPalindrome(int number) { 

    return (number == reverse(number)); 

} // end isPalindrome method 

} // end class 
+3

查看打印格式化文本。 https://docs.oracle.com/javase/tutorial/java/data/numberformat.html –

回答

0

您需要使用String.format對齊文本,然後使用print,如下圖所示:

while (numberPrinted < NUMBER_OF_PALINPRIME) { 
    if (isPrime(testedNumber) && isPalindrome(testedNumber)) { 
    numberPrinted++; 
    System.out.print(String.format("%6s ", testedNumber));//formats to 6 positions 

     if (numberPrinted % 10 == 0) { 
      System.out.println(); 
     } 
    } 
    testedNumber++; 
} 

此外,作爲一個方面說明,確保您的代碼是否正確indentated如此,這將是更具可讀性,因此它不需要不必要的註釋,如第一個if,第二個if等。