ファイルの内容を出力し、ファイルから文字数と単語数を出力する次のコードを作成しました
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);
}
}
問題は、最初の while ループのみが実行されていることです。その理由は、最初の while ループの sc.nextLine である可能性があると思います。
それを修正する方法はありますか?他の while ループも機能するようにしたい