import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class lab{
public static void main(String[] args)throws Exception{
Scanner in=new Scanner(System.in);
String path=in.next();
int count=0;int n=0;int i;String[] arr=new String[10];
InputStreamReader isr=new InputStreamReader(new FileInputStream(path));
BufferedReader br=new BufferedReader(isr);
while(br.read()!=-1){
String s=br.readLine();
count=s.length();
if(count>n)
n=count;
}
for(i=0;br.read()!=-1;i++){
String str=br.readLine();
count=str.length();
if(count==n) {
arr[i]=str;
}
}
isr.close();
for(int j=0;j<i;j++)
System.out.print(arr[i]+" ");
System.out.println(arr[i]);
}
}
http://stackoverflow.com/questions/14908209/output-the-longest-word-in-a-text-file
目测 bigWord.lenght()修改为bigWord.length()
因为执行完
while(br.read()!=-1){
String s=br.readLine();
count=s.length();
if(count>n)
n=count;
}
时,文件已经读完。
再再for循环里面执行br.read()时,会直接返回-1,也就是说你的for循环没起作用、
这样写应该可以吧
String s = null;
String maxlenstr =null;
while((s=br.readLine())!=null){
count=s.length();
if(count>=n)
{
n=count;
maxlenstr = s;
}
然后s就是最后一个最长的单词。
ps:其实遇到这样的问题,楼主可以单步走几次。然后就出答案了,而且对BufferedReader理解也会更深
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
InputStreamReader isr = new InputStreamReader(new FileInputStream(in.next().trim()));
in.close();
isr.close();
BufferedReader br = new BufferedReader(isr);
// 最大长度
int max = 0;
List<String> arStr = new ArrayList<String>();
String str;
// 遍历每行并更新最长单词列表
while ((str = br.readLine()) != null) {
if (max > str.length()) {
continue;
} else if (max == str.length()) {
arStr.add(str);
} else {
arStr.clear();
max=str.length();
arStr.add(str);
}
}
// 输出
for(String s:arStr){
System.out.println(s);
}
}
}