Java 读取一个序列直到空行结束
我正在写一个Java程序。我需要关于程序输入的帮助,这是一个包含两个由一个或多个空格分隔的标记的行序列Java 读取一个序列直到空行结束,java,object,methods,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 = readIn
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);
}
}
最好使用
value.trim().length()
trim()
方法将删除额外的空格(如果有)
另外,
String
被分配给Customer
,在分配对象之前,您需要使用Customer
类型的String
创建一个对象。尝试此代码。。。您可以将要读取的文件放在“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);
}
}
}
import java.io.*;
导入java.util.ArrayList;
公共类读取文件{
静态ArrayList AL=新ArrayList();
公共静态void main(字符串[]args){
试试{
BufferedReader br=新的BufferedReader(新的文件阅读器(“stuff.txt”);
字符串基线;
而((datLine=br.readLine())!=null){
AL.add(datLine);//将文本行添加到ArrayList
System.out.println(datLine);//打印行
}
System.out.println(“标记化…”);
//循环字符串数组
对于(字符串x:AL){
//根据直线之间的间距将每条直线拆分为2段
字符串[]标记=x.split(“”);
//循环遍历令牌数组
对于(int j=0;j