2016-12-06 61 views
-5
import java.util.Scanner; 
public class exam2015q2 
{ 
    public static void main (String args[]) 
    { 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Eneter a number"); 
     int num = scan.nextInt(); 
     int num1 = num-1; 
     int count = 0; 

     if(num % 2 == 0) 
     { 

      count++; 

      System.out.println(+num+ " Is an even number"); 
     } 
     else 
     { 
      System.out.println(num+" Is an odd number"); 
     } 

     boolean isPrime = true; 

     do { 

      if(num % num1 == 0) 
      { 
       isPrime = false; 
       break; 
      } 
      num1--; 
     } 
     while(num1 >= 2); 
     if(isPrime == true) 
     { 
      System.out.println(num +" is a prime number as it is only divisible by 1 and " +num); 
     } 
     else 
     { 
      System.out.println(num +" is NOT a prime number.It is divisible by " +count); 

     } 
    } 
} 

在這方面,我需要輸出,如果它不是一個素數,然後我們要輸出到打印出whta數是整除什麼號碼是整除,但我不能打印出來。我需要幫助這個能有人給我如何通過如果一個數是不是素數那麼就需要通過

+3

[爲什麼「有人可以幫我嗎?」不是一個真正的問題?](http://meta.stackoverflow.com/q/284236/18157)和 [給學生打開信函的問題](http: //meta.softwareengineering.stackexchange.com/q/6166/989) –

+0

爽兄弟,這不是一個問題howrk其BTW考試問題 – brazil

+3

切勿使用代碼(isPrime ==真)。您使用布爾值的原因是爲了避免比較,因爲比較已經完成。 – Grayson

回答

1
public static void main (String args[]) 
    { 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Eneter a number"); 
     int divisibleBy; 
     int num = scan.nextInt(); 
     int num1 = num-1; 
     int count=0; 

     if(num%2==0) 
     { 
      count++; 
      System.out.println(+num+ " Is an even number"); 
     } 
     else 
     { 
      System.out.println(num+" Is an odd number"); 
     } 
     boolean isPrime = true; 
     do{ 
      if(num%num1==0) 
      { 
       divisibleBy = num1; 
       isPrime = false; 
       break; 
      } 
      num1--; 
     } 
     while(num1>=2); 
     if(isPrime == true) 
     { 
       System.out.println(num +" is a prime number as it is only divisible by 1 and " +num); 
     } 
     else 
     { 
      System.out.println(num +" is NOT a prime number.It is divisible by " +divisibleBy); 



} 
} 
0

以獲取整除的數只需更改顯示的變量數整除您的發言從countnum1建議,因爲你在do循環確定那num已經可以除以num1

else{ 
    System.out.println(num +" is NOT a prime number.It is divisible by " +num1); 
} 

你完全可以在你的程序擺脫count,因爲它顯示。

相關問題