從文件計數的單詞和字符數我寫了下面的代碼來打印文件的內容,並從文件錯誤在Java中
import java.io.*;
import java.util.*;
class Ass53
{
public static void main(String args[]) throws Exception
{
File file=new File("sample.txt");
Scanner sc=new Scanner(new FileInputStream(file));
String line,line1;
int count1=0;
int count=0;
/*Loop for printing contents of file*/
while(sc.hasNextLine())
{
line=sc.nextLine();
System.out.println(line);
}
/*loop for counting number of character in file*/
while(sc.hasNext())
{
line1=sc.next();
for(int i=1;i<=line1.length();i++)
count1++;
}
System.out.println(count1);
/*loop for counting number of words in a file*/
while(sc.hasNext())
{
sc.next();
count++;
}
System.out.println("Number of words: " + count);
}
}
問題打印字符和文字的數量是隻有也先循環正在執行。我猜想原因可能是sc.nextLine for first while while循環。第一次while循環sc指向沒有我猜測?
有什麼方法可以解決它嗎? 我希望我的其他while循環也可以工作
OK亞當日Thnx我得到了我的錯誤 – Amol 2013-02-24 18:37:36