# Java第八週[JPA303~305 完美數(判斷因質數)、while、do_while迴圈運用、for迴圈+if判斷式]
#### 複習用
## 開始解題(JPA303~305):
### 第一題(JPA303)-完美數[判斷因數公式]:

解答:
```java
import java.util.Scanner; //沒用到
public class JPA303
{
public static void main(String[] args)
{
int i, num, sum = 0;//題給
System.out.printf("1~1000中的完美數有: ");//題給
for(num=1;num<=1000;num++) //設num為1~1000
{
sum=0; //每跑一個num清為0(將總和清為0)
for(i=1;i<num;i++) //判斷因數的公式
{ //尋找num的因數
if(num%i==0)
{
sum+=i; //題目要求條件(完美數-因數相加)
}
}
if(sum==num) //題目要求條件(完美數相等)
{
System.out.printf("%d ",num); //題給
}
}
System.out.printf("\n"); //題給
}
}
```
---
### 第二題(JPA303_2)-列出2~1000哪些是質數?[判斷因數公式]:

神奇小手手 ヾ(*´∇`)ノ
解答:
```java
import java.util.Scanner;
public class JPA303_2
{
public static void main(String[] args)
{
int i, num,count=0;
System.out.printf("2~1000中的質數有: ");
for(num=2;num<=1000;num++)
{
count=0;
for(i=1;i<=num;i++)
{ if(num%i==0)
{
count++; //質數判斷(加總因數)
}
}
if(count==2) //質數判斷(1和本身)
{
System.out.printf("%d ",num);
}
}
System.out.printf("\n");
}
}
```
---
### 第三題(JPA304)-餐點費用[while迴圈]:
#### while迴圈特殊用法
當圈數未知時,使用while(前測式迴圈)
```java=1
while(true) //條件永遠成立
{
break; //因為沒有條件,所以會有無窮迴圈 //因此要使用break強制跳出
}
```

解答:
```java
import java.util.Scanner;
public class JPA304
{
static Scanner keyboard=new Scanner(System.in);
public static void main(String[] args)
{
int total = 0; //總金額
int s = 0; //輸入的金額 (餐點費)
int count = 0; //用餐人數 (題設五位朋友)
double average; //計算平均
while(true) //無窮迴圈
{
System.out.print("Please enter meal dollars or enter -1 to stop: ");
s=keyboard.nextInt();
if(s!=-1) //無窮迴圈 //(=-1)代表輸入完畢
{
total+=s; //加總金額
count++; //算 幾道菜,為了求平均值
}
else //s=-1
{
break; //while強制跳出,不然他會一直跑
}
}
average=(double)total/count; //(double)強制浮點數
System.out.println("餐點總費用:" + total);
System.out.printf(" %d 道餐點平均費用為: %.2f \n",count,average);
}
}
```
---
### 第四題(JPA304_2)餐點費用-[do while迴圈]:
* 改用do while解答

解答:
```java
import java.util.Scanner;
public class JPA304_2
{
static Scanner keyboard=new Scanner(System.in);
public static void main(String[] args)
{
int total = 0;
int s = 0;
int count = 0;
double average;
do
{
System.out.print("Please enter meal dollars or enter -1 to stop: ");
s=keyboard.nextInt();
total+=s; //加總金額
count++; //算 幾道菜,為了求平均值
}while(count<5); //限定5筆以內(已給條件,自動跳出)
average=(double)total/count;
System.out.println("餐點總費用:" + total);
System.out.printf(" %d 道餐點平均費用為: %.2f \n",count,average);
}
}
```
---
### 第五題(JPA305)-迴圈階乘計算[if判斷+階乘計算]:

解答:
```java
import java.util.Scanner;
public class JPA305
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
test();
test();
test();
}
public static void test()
{
System.out.print("Please enter one value: ");
int n=keyboard.nextInt();
int result=1; //用乘的,所以不能乘0
if((n>0)&&(n<=10)) //1~10
{
for(int i=1;i<=n;i++)
{
result*=i; //用乘的
}
System.out.printf("%d!: %d\n",n,result);
}
else
{
System.out.println("Error,the value is out of range.");
}
}
}
```
---
最後編輯時間:2021/4/17 8:57am.
###### tags: `JAVA課堂學習` `複習用` `高科大`