English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

剛學java不久;

不太會寫;誰能幫幫忙><

題目:利用while判斷使用者輸入一整數是否為質數!

急><~~~

Thanks.....

2006-12-31 06:52:31 · 2 個解答 · 發問者 Anonymous in 電腦與網際網路 程式設計

2 個解答

import java.io.*;
public class Demo
{
public static void main(String argv[])throws IOException
{
BufferedReader keyin=new BufferedReader(
new InputStreamReader(System.in));
System.out.print("請輸入您的數值:");
int a=Integer.parseInt(keyin.readLine());
while(a%2!=0)
{
System.out.println("您輸入的"+a+"是質數");
break;

}
if (a%2==0)
{
System.out.println("您輸入的"+a+"不是質數");
}





}
}

2007-01-01 18:22:09 · answer #1 · answered by Cin 2 · 0 0

請參考我的做法。

import java.io.*;

public class PrimeTest {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("請輸入一個正整數:");
int x = Integer.parseInt(br.readLine());

boolean isPrime = true;
for (int i = 2; i <= x/2; i++) {
if (x % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) System.out.println(x + " 為質數");
else System.out.println(x + " 不為質數");
}
}

2007-01-02 09:28:09 · answer #2 · answered by ? 7 · 0 0

fedest.com, questions and answers