java.util.Scanner應用詳解

來源:互聯網
上載者:User

java.util.Scanner應用詳解

 java.util.Scanner擷取輸入的整數,長整型,字串等:

 代碼如下  

/package com.color.program.ball;
 
import java.util.Scanner;
 
public class ScannerTest {
 
 public static void main(String[] args) {
  Scanner s = new Scanner(System.in);
  //receive string
  String str = s.next();
  
  //receive integer
  Integer i = s.nextInt();
  
  //receive double
  Double d = s.nextDouble();
  
  System.out.println(str+i+d);
 }
}
 
 
如用三元運算子判斷一個數是奇數還是偶數:

import   java.util.Scanner;
 
public   class   Ou {
 public   static   void  main(String[]  args)  {
 
 System.out.println("請輸入一個整數:");
 Scanner     reader = new  Scanner(System.in);
 long    a =  reader.nextLong();
 String str = (a%2 )==0   ?     "偶數":"奇數";
 System.out.println("結果是:"+str);
 
 
 }
 
 
 
}

 
一、掃描控制台輸入
這個例子是常常會用到,但是如果沒有Scanner,你寫寫就知道多難受了。
當通過new Scanner(System.in)建立一個Scanner,控制台會一直等待輸入,直到敲斷行符號鍵結束,把所輸入的內容傳給Scanner,作為掃描對象。如果要擷取輸入的內容,則只需要調用Scanner的nextLine()方法即可。

 代碼如下  
/**
* 掃描控制台輸入
*
* @author leizhimin 2009-7-24 11:24:47
*/
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);
}
}
}
請輸入字串:
234
>>>234
wer
>>>wer
bye
>>>bye
exitProcess finished with exit code 0

先寫這裡吧,有空再繼續完善。
二、如果說Scanner使用簡便,不如說Scanner的構造器支援多種方式,構建Scanner的對象很方便。
可以從字串(Readable)、輸入資料流、檔案等等來直接構建Scanner對象,有了Scanner了,就可以逐段(根據正則分隔式)來掃描整個文本,並對掃描後的結果做想要的處理。

 代碼如下  

package test;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.MatchResult;
 
public class TestScanner {
 
 public static void main(String[] args) throws FileNotFoundException {
 // 鍵盤輸入
 Scanner sc = new Scanner(System.in);
 System.out.println(sc.nextInt());
 
 System.out.println("---------------");
 
 // 文本掃描
 Scanner sc2 = new Scanner(new File("D://1.txt"));
 while (sc2.hasNextDouble()) {
 System.out.println(sc2.nextDouble());
 }
 
 System.out.println("---------------");
 
 // 正則解析
 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();
 
 System.out.println("---------------");
 
 // 正則-匹配組
 String input2 = "1 fish 2 fish red fish blue fish";
 Scanner s2 = new Scanner(input2);
 s2.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
 MatchResult result = s2.match();
 for (int i = 1; i <= result.groupCount(); i++)
 System.out.println(result.group(i));
 s.close();
 }
 
}


以下代碼使 long 類型可以通過 myNumbers 檔案中的項分配:

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

 
三、Scanner預設使用空格作為分割符來分隔文本,但允許你指定新的分隔字元(支援Regex)
使用預設的空格分隔字元:
 

 代碼如下  
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
......asdfkl
lasProcess finished with exit code 0
將注釋行去掉,使用空格或逗號或點號作為分隔字元,輸出結果如下:
123
asdf
sd
45
789
sdf
asdfl
sdf
sdfl
asdfasdfkllas
Process finished with exit code 0

再來個例子,根據pattern字串來匹配

 代碼如下  
package test;
 
import java.util.Scanner;
import java.util.regex.MatchResult;
 
public class TestScanner2 {
 
 public static void main(String[] args) {
 String data = "127.0.0.1@21/10/2005\n" + 
     "128.0.0.11@3/11/2006\n" + 
   "129.132.111.111@4/2/2007\n" + 
   "130.0.0.1@15/1/2008\n" + 
   "[Next log section with different format]";
 Scanner s = new Scanner(data);
 String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@(\\d{1,2}/\\d{1,2}/\\d{4})";
 while(s.hasNext(pattern)) {
 s.next(pattern);
 MatchResult mr = s.match();
 System.out.format("ip = %-15s, data= %10s\n", mr.group(1), mr.group(2));
 }
 }
 
}
 

useDelimiter(Pattern pattern)這個方法是Scanner中用於設定分隔字元的,預設情況下scanner分割符是空格,你這 個程式中就是用Regex來設定分隔字元,"\\s*fish\\s*"前面的一個\\s*表示空格出現0次或多次接著出現fish接著出現0個或多個空 格,只要scanner掃描遇到的資料符合這個Regex,前面的就當一個資料就可以用Scanner中的next()返回取得資料。  
 

 代碼如下  
//output
ip = 127.0.0.1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; , data= 21/10/2005
ip = 128.0.0.11&nbsp;&nbsp;&nbsp;&nbsp; , data=&nbsp; 3/11/2006
ip = 129.132.111.111, data=&nbsp;&nbsp; 4/2/2007
ip = 130.0.0.1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; , data=&nbsp; 15/1/2008

 
總結:1)多種輸入,File,input,System.in,String等
            2)與正則結合使用
            3)實現了Iterator介面
四、一大堆API函數,實用的沒幾個
(很多API,注釋很讓人迷惑,幾乎毫無用處,這個類就這樣被糟蹋了,啟了很不錯的名字,實際上做的全是齷齪事)
下面這幾個相對實用:
delimiter()
返回此 Scanner 當前正在用於匹配分隔字元的 Pattern。
hasNext()
判斷掃描器中當前掃描位置後是否還存在下一段。(原APIDoc的注釋很扯淡)
hasNextLine()
如果在此掃描器的輸入中存在另一行,則返回 true。
next()
尋找並返回來自此掃描器的下一個完整標記。
nextLine()
此掃描器執行當前行,並返回跳過的輸入資訊。
五、漸進式掃描檔案,並逐行輸出
看不到價值的掃描過程

 代碼如下  

public static void main(String[] args) throws FileNotFoundException {
InputStream in = new FileInputStream(new File("C:\\AutoSubmit.java"));
Scanner s = new Scanner(in);
while(s.hasNextLine()){
System.out.println(s.nextLine());
}
}
package own;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import com.verisign.uuid.UUID;
/**
* @author wangpeng
*
*/
public class AutoSubmit {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
...在此省略N行
Process finished with exit code 0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.