Java
===
> Cheat Sheet ^^
References: NCKU 李信杰教授
Introduction
---
- Hello-World !
```
package package_name
public class _HelloWorld_Class {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("You're in the " + args[0] + "!");
}
}
```
- Class!
```
public class Duck {
public boolean canfly = false;
public void quack(){
System.out.println("Quack!!");
}
}
Duck duck = new Duck();
```
I/O
---
- print`System.out.print("Hello\n");`
- printf `System.out.printf("Hello%n");`
> in Java, "%n" == ""\n" == change line;
> "%5.2f" means 5 character, 2 of them are float
>
- println `System.out.println("Hello");`
- args `args[0]`
Basic Informations
---
> C-like Language
> - // /* */
> - ......;
> - import ...;
> - %d %6.2f \n \'
> - if(){} else if(){} else{}
> - switch(){case: break; default:}
> - while({}
> - do{}while();
> - for( Initializing; Boolean; Update){}
> - break; continue;
> - && || !
> - string1.equalsIgnoreCase(string2)
- Labeled **break**
```
loop1: for(..){
for(...){
if(...) break loop1;
}
}
```
- Exit `System.exit(0);`
- change type: `a = (int) 2.9` // a = 2
> Compile: `javac HelloWorld.jave`
> Execute: `java HelloWorld`
> Special way to use:
> `a = b = c = 0;`
Basic Packages
---
- String: `String str = "Number is " + 5` // str = "Number is 5"
- .length()
- .equals()
- `str.equals("Number is ")`
- .equalsIgnoreCase()
- .toLowerCase()
- .toUpperCase()
- .trim()
- trim 'space' and '\n'
- .charAt()
- `str.charAt(0)` // return 'N'
- .substring()
- `str.substring(7)` // return "is "
- `str.substring(1, 3)` // return "umb"
- .indexOf()
- indexOf(A_string)
- indexOf(A_string, start)
- .lastIndexOf()
- .compareTo()
- .compareToIgnoreCase
more Packages
---
- NumberFormat `import java.text.NumberFormat;`
- init: `getCurrencyInstance()`
- `NumberFormat moneyFormater = NumberFormat.getCurrencyInstance();`
- Locale `import java.util.Locale;`
- .TAIWAN
- `NumberFormat moneyFormater2 = NumberFormat.getCurrencyInstance(Locale.TAIWAN)`
- .US
- .JAPAN
- .FRANCE
- .ITALY
- .CHINA
- DicimalFormat `import java.text.DecimalFormat;`
- init: `new DicimalFormat("00.000")`
- `DecimalFormat pattern00dot000 = new DecimalFormat("00.000")`
- `"#0.###E0"` means 1 or 2 digits before point
- `System.out.println(pattern00dor000.format(a));`
- Scanner `import java.util.Scanner`
- init: `new Scanner(System.in)`
- `Scanner Keyboard = new Scanner(System.in);`
- `int number = keyboard.nextInt();`
- `double d1 = keyboard.nextDouble();`
- `String word1 = keyboard.next();` read a word
- `String line = keyboard.nextLine();` read whole line
- Use .nextLine() to escape from the end of 'nextInt()' 'nextDouble()'...
- Delimiter: Separate words
- `keyboard.useDelimiter("#")`
- which means 'a#b#c' in .next() will be separated into 'a' 'b' 'c'
- FileInputStream (好像要是絕對路徑才會成功)(or `./src/...`)
- `import java.io.FileInputStream;`
- `import java.io.FileNotFoundException;
- `fileIn = new Scanner(new FileInputStream("data.txt"));`
- open file in "**try/catch**" block
- use "**nextInt()**", "**nextLine()**"...
```
try{
fileIn = new Scanner(new FileInputStream("PathToFile"));
}
catch(Exception e){
System.out.println("File not found.");
e.printStackTrace();
System.exit(0);
}
if( fileIn.hasNextLine() == true ){
str = fileIn.readLine();
}
else{
}
```
> **相對路徑會不成功問題:** 因為編譯的執行/儲存位置關係,就算是用File的getAbsolutePath也沒用。因此,要用"./src/package_name/file_name"來作為FileInputStream的輸入值。
- Random `import java.util.Random`
- `Random rnd = new Random();`
- `int i = rnd.nextInt(10);`
- Math `import java.lang.*;`
- .pow
- `Math.pow(var, order)`
- .sqrt
- `Math.sqrt(var)`
- StringTokenizer `import java.util.StringTokenizer`
- separated by...
- space: `StringTokenizer st = new StringTokenizer(str);`
- delimiters: `StringTokenizer st = new StringTokenizer(str, delimiters);`
- .hasMoreTokens()
- return boolean
- .nextToken()
- return String
- .nextToken(delimiters)
- return String
- .countTokens()
- return int
- sample
```
import java.util.StringTokenizer;
public class StringTokenizerTest {
public static void main(String[] args) {
String in = "Hello,World,Java";
StringTokenizer st = new StringTokenizer(in, ",");
while(st.hasMoreTokens()) {
String token = st.nextToken();
System.out.println(token);
}
}
```
Class
---
- sample
```
public class Duck {
public boolean canfly = false;
public void quack(){
System.out.println("Quack!!");
}
}
Duck duck = new Duck();
```
- init class: `public class ClassName{}
- Var `public boolean canfly = false;`
- methon `public void quack(){}`
- if void: `return;`
- else: (add)
```
public String eat(String food){
String message = "Thank you for choosing" + food + "!";
return message;
}
Duck.eat("foodpanda")
```
> result: "Thank you for choosing foodpanda !"
- Constructor `public ClassName(anyParameter){code}`
- must be void. Can't add "void" in announcement.
- use: `Duck duck = new duck("foodpanda")`
- new object: `ClassName VarName = new ClassName`
- static method:
- Don't have to `new`
- no `this`
-
- Sample:
```
public class StaticTest {
public static void main(String[] args) {
int sum = Tool.add(1,1);
System.out.println(sum);
}
}
public class Tool {
public static int add(int a, int b){
return a+b;
}
}
```
- File `import java.io.File`
- `File file = new File(addr);`
- 
- 
For Your Informations
---
> Type:

> principle

> printf:

> Scanner:


