1.網頁解碼

題目如下:

這一題我採用打開網頁之後提取出裏面的要分析的代碼,然後寫一個java程序通過控制檯讀入這些代碼,用正則表達式讀取每一行的數字,相加即可出結果,代碼如下 : 

     

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebNum {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		String temp = null;
		Pattern pattern = Pattern.compile("[0-9]+");//寫正則表達式,[0-9]+代表匹配儘可能長的整數
		long result = 0;
		Matcher matcher = null;
        while(!(temp=sc.nextLine()).equals("#")){   //當沒有輸入#號的時候會一直讀取下一行
        	matcher = pattern.matcher(temp);   //用編譯好的正則去匹配讀入的這一行代碼,得到matcher對象
        	if(matcher.find()){//如果匹配成功
        		result += Integer.parseInt(matcher.group(0));  //將匹配到的數字字符串轉換爲整數加到結果中
        	}
        }
        System.out.print(result);
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章