读取序列直到空行

时间:2014-03-03 17:37:22

标签: java object methods

我正在编写一个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);
 }
}

2 个答案:

答案 0 :(得分:0)

最好使用value.trim().length()

trim()方法将删除额外的空格(如果有的话)。

另外String已分配给Customer,您需要在分配String之前创建Customer类型的对象。

答案 1 :(得分: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);

}

}



}
相关问题