我想要打印出有多少字母「a」。 它不斷給我0 ...任何幫助?計算字符串中出現的字符
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File myfile = chooser.getSelectedFile();
try {
Scanner in = new Scanner(myfile);
String word = in.nextLine();
int counter = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == 'a') {
counter++;
}
}
System.out.println("# of chars: " + counter);
} catch (IOException e) {
System.err.println("A reading error occured");
}
}
打印'word',你會得到什麼? – arshajii
您是否嘗試在循環之前打印「單詞」? –
您只檢查第一行。文件中的第一行是否有'a'? – Adarsh