---
# System prepended metadata

title: JAVA教學---Flow Control
tags: [JAVA教學]

---

# JAVA教學---Flow Control

###### tags: `JAVA教學`

## 目錄
[TOC]


## Using == with Object (例如String)
```
若 == 用於比較 primitive type ，則是直接比較內容
若 == 用於比較 Object ，例如 String，則是比較 Object 的 memory location
```
```java=
public class demo1 {
	public static void main(String[] args) {
		String a = new String("Java");
		String b = new String("Java");
		System.out.println(a);
		System.out.println(b);
		if(a==b) //flase，不會印
			System.out.println("a==b");
		if(a.equals(b))  // ture，會印
			System.out.println("a equals to b");
			
		String c = "Java";
		String d = "Java";
		System.out.println(c);
		System.out.println(d);
		if(c==d) // ture，在同個String Buffer，會印
			System.out.println("c==d");
		if(c.equals(d)) // ture，會印
			System.out.println("c equals to d");
	}
}
```
:::warning
在沒有 Override 或 Overload 的情況下，任何 object 的預設 equals 方法皆是比較 2 個物件的 memory location 是否相同，如下。

String 的 equals() 是比較字串內容
String 的 == 是比較 memory location
:::
```java
System.out.println(object1.equals(object2)); // 比 memory location 
System.out.println(object1 == object2);      // 比 memory location 
```


## &&(||) 和 &(|) 的差異
```
&&只要前面為flase，後面就不會去算，直接回傳false
&前後都會算，即便前面為flase

||只要前面為true，後面就不會去算，直接回傳true
|前後都會算，即便前面為true
```
```java=
public class demo {
	public static void main(String[] args) {
		int a = 1;
		int b = 0;
		//前面為false，因為是&&，後面不會再去算
		if ((b !=0) && ((a/b) >=2))  
		System.out.println("bingo");
		
		//前面為false，但是是用&，所以後面也會算
		if ((b !=0) & ((a/b) >=2)) // a/b為除0，故compiler會報錯	 
		System.out.println("bingo again");
	}
}
```

## Evaluating Expressions
>Instead of relying on precedence and associativity rules, it is best to 
include most parentheses, except where the intended meaning is obvious

![](https://i.imgur.com/bS3Ggcu.png)

## while
```java
while (Boolean_Expression)
        Statement
```
```java
while (Boolean_Expression)
{
    Statement_1
    Statement_2
    Statement_Last
}
```

## do-while
>一定會執行while迴圈內敘述一次，且while後面要加 ;
```java
do
Statement
while (Boolean_Expression);
```
```java
do 
{
    Statement_1
    Statement_2
    Statement_Last
}while(Boolean_Expression);
```

## for
```java
for (Initializing; Boolean_Expression; Update)
    Statement
```
```java
for (Initializing; Boolean_Expression; Update){
    Statement1
    Statement2
    .....
}
```

## for 和 array 語法糖
```java=
// declaring an array
int arr[] = { 12, 13, 14, 44 };
int total = 0;
// traversing the array with for-each loop
for (int i : arr) {  // 跑4次
    System.out.println(i);
    total = total + i;
}
System.out.println("Total: " + total);  // 印83
```

## break
用break會跳出最近的loop，不是entire loop。
```java=
for(int i=0;i<=10;i++){
    System.out.println("i="+i);
    for(int j=0;j<=10;j++){
        System.out.println("j="+j);
        break;
    }
}
```
>output
i=0
j=0
i=1
j=0
....
i=10
j=0
```java=
loop1: for(int i=0;i<=10;i++){
	System.out.println("i="+i);
	for(int j=0;j<=10;j++){
		System.out.println("j="+j);
		break loop1;  // 功能相同於只有 break;
	}
}
```
>output
i=0
j=0

## exit
呼叫exit會直接終止program。
```java
System.exit(0);
```

## Random Numbers
引入 java.util package 的 Random class
```java
import java.util.Random;
```
宣告物件
```java
Random randomGenerator  = new Random();
```
產生int隨機數
```java
int i = randomGenerator.nextInt(10); // 0 <= i < 9
```
產生double隨機數
```java
double a = randomGenerator.nextDouble(); // 0.0 <= a < 1.0
double b = randomGenerator.nextDouble(10); // 0.0 <= b < 10.0
```
demo 模擬硬幣
```java=
import java.util.Random;

public class demo1 {
	public static void main(String[] args) {
		Random randomGenerator = new Random();
		int counter = 1;
		int numHeads = 0, numTails = 0;
		int totalCount = 100;
		
		while(counter <= totalCount) {
			System.out.print("Flip number " + counter + ": ");
			int coinFlip = randomGenerator.nextInt(2);
			if (coinFlip == 1) {
				System.out.println("Heads");
				numHeads++;
			}
			else { 
				System.out.println("Tails");
				numTails++;
			}
			counter++;
		}
		float ratio = (float)numHeads/(numHeads + numTails) ;
		System.out.println("Heads ratio = " + ratio + "\n");
	}
}
```
例題計算$\displaystyle\sum_{i=1}^{n} x^2$，輸入x跟n
```java=
import java.util.Scanner;
public class demo1 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.print("Enter a value for x :");
		int x = scanner.nextInt();
		System.out.print("Enter a value for n :");
		int n = scanner.nextInt();
		int frac = (int)Math.pow(x, 2);
		int sum = 0;
		for(int i=1; i<=n; i++)
			sum = sum + frac;
		System.out.println("y = " + sum);
	}
}
```

Please write a program to calculate the values of the following equation: 
$$
{-b \pm \sqrt{b^2-4ac} \over 2a}.
$$

```java=
public class demo1 {
	public static void main(String[] args) {
		double a = 1;
		double b = -3;
		double c = 2;
		double x = (-1*b + Math.sqrt(Math.pow(b,2) - 4*a*c)) / (2*a);
		System.out.println(x);
	}
}
```