# 變數與輸出

### 一、println 與 變數 使用

在Hello Java 程式中我們有用到println 這個用法：

```
 System.out.println("Hello Java!");
```

本章就先從這部分開始說起～\
以下：

```
public class class01 {

	public static void main(String[] args) {
		int num;
		num=5;
		System.out.println("I have "+num+" books");
		System.out.println("You have "+num+" books, too");

	}

}
```

我們可以先想想，這個的輸出結果會是如何。\
想完之後再上 eclipse 執行看看結果如何。

{% hint style="info" %}
比對兩次的是否相同後，在看以下的程式分析唷！
{% endhint %}

本章的重點如下：

```
int num;
num=5;
	System.out.println("I have "+num+" books");
	System.out.println("You have "+num+" books, too");
```

`int num;`是宣告 num 為一個整數型態的變數。

`num=5;`是把數值5設定給整數變數num存放。

```
System.out.println(“I have “+num+” books”);
System.out.println(“You have “+num+” books, too”);
```

`System.out` 是標準輸出；`println` 則是 print line 的縮寫，意指將後方括號中的內容印到輸出設備，如螢幕。因此印出 I have 5 books 之後會換行也就是把游標移到下一行的開端列印。

![輸出結果](https://2439647256-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4NDwp0sFRvD07cdujE%2F-M4X5ohX1Sy4Gxu_VyG6%2F-M4X6ag5ZC4u26hBvZXf%2Fimage.png?alt=media\&token=5b1f78aa-6b30-47b2-9052-55312df58c41)

我們可以發現他會直接印出雙引號內的內容，而num 的部分為數值5。 簡單的對照圖如下：由於已給定num變數為數值5，因此輸出時將會輸出5。

![](https://2439647256-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4NDwp0sFRvD07cdujE%2F-M4X5ohX1Sy4Gxu_VyG6%2F-M4X6eUAdeyStRmmQ7TE%2Fimage.png?alt=media\&token=9fd6e0ff-58da-4766-a064-ffec58c8dbfc)

### 二、println 與 print 比較

讓我們改試試以下程式碼：

```
public class class01 {

	public static void main(String[] args) {
		int num;
		num=5;
		System.out.print("I have "+num+" books");
		System.out.println("You have "+num+" books, too");

	}

}
```

與上面的輸出結果有何差別？

![執行結果，會發現You have 5 books, too 緊連著前一句的屁股](https://2439647256-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4NDwp0sFRvD07cdujE%2F-M4X5ohX1Sy4Gxu_VyG6%2F-M4X6p2DJ5w0zHAbQgDD%2Fimage.png?alt=media\&token=36f18c13-e898-4d28-87b8-247455847856)

在這邊補充說明 print 與 println 的小差異：

{% hint style="info" %}
*println 是有換行*\
\&#xNAN;*print 無換行*
{% endhint %}
