1. 程式人生 > >Java關於Scanner類的心得

Java關於Scanner類的心得

類 Scanner

一個可以使用正則表示式來解析基本型別和字串的簡單文字掃描器。

java.util.Scanner是Java5的新特徵,主要功能是簡化文字掃描。這個類最實用的地方表現在獲取控制檯輸入,其他的功能都很雞肋,儘管Java API文件中列舉了大量的API方法,但是都不怎麼地。

Scanner一般用於使用者輸入,可以對輸入的文字進行操作

重要方法摘要


          如果此掃描器的輸入中有另一個標記,則返回 true。

          此掃描器執行當前行,並返回跳過的輸入資訊。
next()
          查詢並返回來自此掃描器的下一個完整標記。

Scanner可以使用不同於空白的分隔符。下面是從一個字串讀取若干項的例子

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(); 

二.如果說Scanner使用簡便,不如說Scanner的構造器支援多種方式,構建Scanner的物件很方便。



可以從字串(Readable)、輸入流、檔案等等來直接構建Scanner物件,有了Scanner了,就可以逐段(根據正則分隔式)來掃描整個文字,並對掃描後的結果做想要的處理。

1.從控制檯輸入

public class TestScanner { 
        public static void main(String[] args) { 
                Scanner s = new Scanner(System.in); 
                System.out.println("請輸入字串:"); 
                while (true) { 
                        String line = s.nextLine(); 
                        if (line.equals("exit")) break; 
                        System.out.println(">>>" + line); 
                } 
        } 
}

2.從檔案構造Scanner的舉例

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ScannerTest {
	public static void main(String[] args) throws IOException{
		Scanner sc=new Scanner(new File("D:\\txt.txt"));
		
		
		while(sc.hasNextLine())
		{
			System.out.println(sc.nextLine());
		}
		sc.close();
	}
}
3.使用分隔符
public static void main(String[] args) throws FileNotFoundException { 
                Scanner s = new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las"); 
                s.useDelimiter(" |,|\\."); 
                while (s.hasNext()) { 
                        System.out.println(s.next()); 
                } 
        }

輸出:

123 
asdf 
sd 
45 
789 
sdf 
asdfl 
sdf 
sdfl 
asdf 

注:個人想說,這裡只是列出了部分重要的方法和使用,想要有更細微的使用,一定要閱讀API文件

轉自:https://blog.csdn.net/gongxifacai_believe/article/details/54933287

https://blog.csdn.net/scythe666/article/details/51980596/