筆記 Java Scanner
格式字元 | 作用 |
%% | 在字串中顯示% |
%d | 以10 進位整數方式輸出,提供的數必須是Byte、Short、 Integer、Long、或BigInteger |
%f | 將浮點數以10 進位方式輸出,提供的數必須是Float、Double 或BigDecimal |
%e, %E | 將浮點數以10 進位方式輸出,並使用科學記號,提供的數必須是Float、Double 或BigDecimal |
%a, %A | 使用科學記號輸出浮點數,以16 進位輸出整數部份,以10 進位輸出指數部份,提供的數必須是Float、Double、BigDecimal |
%o | 以8 進位整數方式輸出,提供的數必須是Byte、Short、 Integer、Long、或BigInteger |
%x, %X | 將整數以16 進位方式輸出,提供的數必須是Byte、Short、 Integer、Long、或BigInteger |
%s, %S | 將字串格式化輸出 |
%c, %C | 以字元方式輸出,提供的數必須是Byte、Short、Character 或 Integer |
%b, %B | 將"true"或"false"輸出(或"TRUE"、"FALSE",使用 %B)。另外,非null值輸出是"true",null 值輸出是"false" |
%t, %T | 輸出日期/時間的前置,詳請看線上API 文件 |
Scanner
//scanner.next(); 取的字串
範例一:
import java.util.Scanner;
public class ScoreArray {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入你的名字");
System.out.printf("哈囉!! %s!\n",scanner.next());
}
}
請輸入你的名字
jj
哈囉!! jj!
//scanner.nextInt(); 取的數字
範例二:
import java.util.Scanner;
public class ScoreArray {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入一個數字");
System.out.printf("你輸入的字串是: %d !\n", scanner.nextInt());
}
}
請輸入一個數字5
你輸入的字串是: 5 !
//取的 1 fish 2 fish red fish blue fish ,字串與數字
範例三:
import java.util.Scanner;
public class ScoreArray {
public static void main(String[] args){
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
}
}
1
2
red
blue
範例四:
import java.util.Scanner;
public class ScoreArray {
public static void main(String[] args) {
System.out.print("請輸入Array的長度: ");
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
int number[] = new int[length];
System.out.print("Array 內容是: ");
for(int i = 0; i < number.length; i++){
System.out.print(number[i] + " ");
number[i] = i;
}
System.out.println();
System.out.print("Array 累加是: ");
for(int j = 0; j < number.length; j++){
System.out.print(number[j] + " ");
}
}
}
請輸入Array的長度: 10
Array 內容是: 0 0 0 0 0 0 0 0 0 0
Array 累加是: 0 1 2 3 4 5 6 7 8 9
readLine()方法會傳回使用者在按下Enter 鍵之前的所有字元輸入,不包括最後按下的Enter 返回字元
範例五:
import java.io.*;
public class ScoreArray {
public static void main(String[] args) throws IOException{
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(System.in));
System.out.print("請輸入一列文字,可包括空白: ");
String text = bufferedReader.readLine();
System.out.println("您輸入的文字: " + text);
}
}
請輸入一列文字,可包括空白: Hello Word !
您輸入的文字: Hello Word !
留言
張貼留言