StringTokenizer类

java.util.StringTokenizer Class

StringTokenizer可以采用分隔符将字符串解析为一个个的词汇单元,一次可以返回字符串内被分割后的某一个词汇单元

public StringTokenizer(String str)

public StringTokenizer(String str, String delim)

****************************************************

public String nextToken()

public boolean hasMoreTokens()

public int countTokens()

注意这是一个动态变化方法,不可以在while循环中调用,因为每调用一次tokens数就会-1;故应该将初始值赋给一个变量,然后再将这个新的变量运用到循环中

****************************************************

StingTokenizer往往和8个基本数据类型的封装类联合使用,因为分割之后的某些词汇单元可能需要当作布尔型或者整型来使用

Integer.toString(10);String.valueOf(10);

Integer.parseInt("10");

 1 public class Generator{
 2     public static SaleItem creatSaleItem(String str, String deli){
 3         StringTokenizer tokenizer = new StringTokenizer(str, deli);
 4             if(tokenizer.countTokens() == 3){
 5                 String isbn = tokenizer.nextToken();
 6                 int unitSold = integer.parseInt(tokenizer.nextToken());
 7                 return new SaleItem(isbn, unitSold, revenue);
 8             }else{
 9                 return null;
10                     }
11             }
12 
13     public static void main(String[] args){
14         String data = "A001_5_2013.54";
15         SaleItem saleItem = creatSaleItem(data, "_");
16         System.out.println("isbn:" + saleItem.getIsbn());
17         System.out.println("unitSold:" + saleItem.getUnitsSold());
18         System.out.println("revenue:" + saleItem.getRevenue());
19         System.out.println("avgPrice:" + saleItem.avg.Price());
20     }
21 }
 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 import java.io.PrintWriter;
 5 import java.util.StringTokenizer;
 6 
 7 public class ConsoleTest {
 8     private static BufferedReader stdIn = 
 9             new BufferedReader(new InputStreamReader(System.in));
10     
11     private static PrintWriter stdOut = 
12             new PrintWriter(System.out, true);
13     
14     private static PrintWriter stdErr = 
15             new PrintWriter(System.err, true);
16     
17     public static void main(String[] args)throws IOException {
18         
19         stdErr.print("Enter three integers on one line:");
20         stdErr.flush();
21         
22         StringTokenizer tokenizer = 
23                 new StringTokenizer(stdIn.readLine());
24         if(tokenizer.countTokens()!=3) {
25             stdErr.println("Invalid input");
26         }else {
27             int firstValue = Integer.parseInt(tokenizer.nextToken());
28             int secondValue = Integer.parseInt(tokenizer.nextToken());
29             int thirdValue = Integer.parseInt(tokenizer.nextToken());
30             int sum = firstValue + secondValue + thirdValue;
31             stdOut.println("sum:" + sum);
32             stdOut.println("sum:" + firstValue + secondValue + thirdValue);
33         }
34     }
35 
36 }

 

posted @ 2020-04-26 07:28  小菜在路上  阅读(271)  评论(0编辑  收藏  举报