我正在使用cat text-file |来处理文件我的终端上的Java my-program
我将数据存储到数组后打印行的结果为null 有谁可以解释为什么?
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
int index = 0;//create index to increment through array
while(scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
count++;
}
if(count < BUFSIZE){
stringArray = new String[count];
}
else{
stringArray = new String[BUFSIZE];
}
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
{
stringArray = expandArray(stringArray,BUFSIZE);//call method to increase array length
}
stringArray[index] = line2;//store line into array at given index
index++;//increment index
}
/*while(sorted){
sorted = false;
for(int i = 0; i < stringArray.length-1; i++){
if(stringArray[i].compareTo(stringArray[i+1]) > 0){
temp = stringArray[i];
stringArray[i] = stringArray[i+1];
stringArray[i+1] = temp;
sorted = true;
}
}
}*/
for(int i = 0; i < stringArray.length; i++){
System.out.println(stringArray[i]);
}
}
}
private static String [] expandArray(String [] array, int extend){
String newArray [] = new String[array.length+extend];//create new array with given array and int as length to extend
//for loop to copy data from old array into new created array
for( int i = 0; i < array.length; i++){
newArray[i] = array[i];
}
return newArray;//return newly created array
}
}
程序气泡对字符串数组进行排序。如果我通过扫描仪文件读取文件很好,但为什么我不捕捉它。 expand array方法是在每次达到最大容量时动态扩展数组。谢谢
答案 0 :(得分:1)
以下是错误的:
Scanner scan2 = new Scanner(System.in);
Scanner scan = new Scanner(System.in);//create new scanner object
基本上,每个扫描程序都会抓取System.in
流,但只能读取一次。您应该将代码更改为仅使用一个扫描程序,然后仅使用一次。
当您编写程序以使用文件时,扫描程序实际上会打开两个文件流,以便可以读取两次,但只有当您拥有一个流时,这将不起作用。
编辑:
这是一个只使用一个Scanner(因此只有一个流)的版本:
Scanner scan = new Scanner(System.in);//create new scanner object
int count = 0;
stringArray = new String[BUFSIZE];
while (scan.hasNextLine()){//while looop to execute if file has length
String line = scan.nextLine();//store line into string input
if (count >= stringArray.length) {
//call method to double array length
stringArray = expandArray(stringArray, stringArray.length);
}
stringArray[count] = line;
count++;
}
// Shrink array to required size
String[] temp = stringArray;
stringArray = new String[count];
System.arraycopy(temp, 0, stringArray, 0, count);
请注意我没有测试过,但从概念上讲,这是如何做到的。
另一种选择是使用ArrayList<String>
,它会自动扩展和缩小。
答案 1 :(得分:1)
Scanner scan = new Scanner(System.in);
List<String> list = new LinkedList<>();
while(scan.hasNext()) list.add(scan.next());
scan.close();
Collections.sort(list);
for(String line : list) System.out.println(line);
洛尔
更新 @JBert:
System.out.println(StringUtils.join(Ordering.<String>natural().sortedCopy(IOUtils.readLines(System.in)), "\r\n"));
looool
答案 2 :(得分:0)
在此代码中
while(scan2.hasNextLine()){
String line2 = scan2.nextLine();
if(index > stringArray.length-1)
如果index大于数组的长度,你正在做某事,但是没有做任何事情。