2014-03-03 54 views
0

我正在編寫一個Java程序。我需要程序輸入的幫助,即包含兩個由一個或多個空格分隔的令牌的一系列行。讀取一個序列直到空行

import java.util.Scanner; 
class ArrayCustomer { 
public static void main(String[] args) { 
    Customer[] array = new Customer[5]; 
    Scanner aScanner = new Scanner(System.in); 
    int index = readInput(aScanner, array); 
} 
} 

回答

0

這是更好地使用value.trim().length()

trim()方法去除,如果任何多餘的空格。

而且String被分配到Customer你需要指定它之前創建一個對象了Customer類型的String的。

0

試試這個代碼...你可以把你想要讀取的文件從「stuff.txt」當前所在的位置。此代碼使用String類中的split()方法標記每行文本直到文件結束。在代碼中,split()方法根據空間拆分每一行。此方法使用正則表達式(例如此代碼中的空白空間)來確定如何標記化。

import java.io.*; 
import java.util.ArrayList; 

public class ReadFile { 

static ArrayList<String> AL = new ArrayList<String>(); 

public static void main(String[] args) { 
    try { 
    BufferedReader br = new BufferedReader(new FileReader("stuff.txt")); 
     String datLine; 
     while((datLine = br.readLine()) != null) { 
       AL.add(datLine); // add line of text to ArrayList 

       System.out.println(datLine); //print line 
     } 
     System.out.println("tokenizing..."); 




     //loop through String array 
     for(String x: AL) { 
       //split each line into 2 segments based on the space between them 
       String[] tokens = x.split(" "); 
      //loop through the tokens array 
      for(int j=0; j<tokens.length; j++) { 
        //only print if j is a multiple of two and j+1 is not greater or equal to the length of the tokens array to preven ArrayIndexOutOfBoundsException 
        if (j % 2 ==0 && (j+1) < tokens.length) { 
          System.out.println(tokens[j] + " " + tokens[j+1]); 
        } 
      } 

     } 


} catch(IOException ioe) { 
     System.out.println("this was thrown: " + ioe); 

} 

} 



} 
相關問題