Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 輸入輸出常用類別:Scanner 詳解

Scanner 是 Java 中取得鍵盤輸入最順手的工具。先看一個實際例子:輸入學生姓名與五門課成績,計算平均。

public boolean DemoTest(){
    Scanner input = new Scanner(System.in);
    System.out.print("請輸入學生姓名");
    String name = input.next();

    int score = 0;
    double sum = 0;
    double average = 0;

    for(int i = 0; i < 5; i++){
        System.out.print("請輸入第[" + (i + 1) + "]門課程成績");
        score = input.nextInt();
        sum += score;
    }

    average = sum / 5;
    System.out.println("學生" + name + "的平均成績為" + average);
    return true;
}

搭配 JUnit 3 的測試程式碼:

package com.ch01;

import junit.framework.Assert;
import junit.framework.TestCase;

public class ScannerTestCase extends TestCase {
    public void testch01Scanner(){
        ScannerTest input = new ScannerTest();
        Assert.assertEquals(true, input.DemoTest());
    }
}

Scanner 到底是什麼

繼承結構:java.lang.Object → java.util.Scanner,並實作了 Iterator<String> 介面。

它是一個能運用正規表達式解析基本型別與字串的簡易文字掃描器。Scanner 會以「分隔模式」把輸入切成一個個標記(token),預設的分隔模式就是空白字元,接著再用各種 next 方法把標記轉成需要的型別。

最常見的用法是從 System.in 讀一個整數:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

也可以從檔案逐項讀取 long:

Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
    long aLong = sc.nextLong();
}

自訂分隔符

分隔符不必是空白。以下範例把 "fish" 當成分隔符:

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。

若想用一條正規表達式一次解析全部標記,可以搭配 findInLine 與 match():

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i = 1; i <= result.groupCount(); i++)
    System.out.println(result.group(i));
s.close();

最後補充一點:預設的空白分隔符是透過 Character.isWhitespace 判定的,而呼叫 reset() 會把分隔符還原成預設的空白模式,無論你之前改成了什麼。

Copyright © Linux教程網 All Rights Reserved