[英]How do I print one letter of a string that was input by the user in Java?
[英]How do I add multiple lines of txt into an array and compare each letter to a user-input letter?
我正在嘗試創建一個程序來讀取 txt 文檔並計算用戶輸入的字母的出現次數。 我的 for 循環索引字母似乎不正確,因為它只讀取文檔的第一行或最后一行。 有任何想法嗎?
txt 文件包含:
Porsche GT2 RS
Lamborghini Huracan Evo
Mercedes Benz S 63 AMG
Merces Benz AMG GT 63s
Ferrari F8 Tributo
程序如下:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class GetOccurChar {
static void GetOccurFile(File f) throws IOException {
System.out.println("What letter do you want to check the occurence for in the file?");
Scanner scan2 = new Scanner(System.in);
char c = scan2.next().charAt(0);
int count = 0;
String str= "";
char[] ch = new char[100];
try {
Scanner scan = new Scanner (f);
while (scan.hasNextLine()) {
str = scan.nextLine().toLowerCase();
for (int i = 0; i < str.length(); i++)
ch[i] = str.charAt(i);
}
scan.close();
for (int i = 0; i < ch.length; i++)
if (ch[i] == c)
count++;
System.out.println(c +" occures " + count + " times in the file.");
System.out.println(ch);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
輸出:
What letter do you want to check the occurence for in the file?
t
t occures 2 times in the file.
ferrari f8 tributo 63so
您的while
循環嘗試將每一行復制到您的ch
數組中,覆蓋該過程中的任何先前行。 在循環之后,僅保留最后一行和尚未覆蓋的前幾行的任何剩余部分。 只有這樣你才能執行搜索,基本上只搜索最后一行。 為了搜索所有行,您必須在迭代行時進行搜索,例如將第二個循環放在第一個循環中:
while (scan.hasNextLine()) {
str = scan.nextLine().toLowerCase();
for (int i = 0; i < str.length(); i++)
ch[i] = str.charAt(i);
for (int i = 0; i < ch.length; i++)
if (ch[i] == c)
count++;
}
請注意,您的數組ch
是一件非常危險的事情,如果任何一行碰巧超過 100 個字符,您的程序就會崩潰。 在您當前的程序中不需要它,您可以直接檢查您的信件而不存儲行:
while (scan.hasNextLine()) {
str = scan.nextLine().toLowerCase();
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == c)
count++;
}
您不需要創建char[] ch = new char[100]
。 您需要做的就是將字符串的每個字符與所需的字符進行比較,並在找到匹配項時增加count
。 此外,請確保在從中獲取所需字符(第一個字符)之前將輸入轉換為小寫,因為您在迭代其字符之前將文件的每一行都轉換為小寫。
static void GetOccurFile(File f) throws IOException {
System.out.println("What letter do you want to check the occurence for in the file?");
Scanner scan2 = new Scanner(System.in);
char c = scan2.next().toLowerCase().charAt(0); // Lower case
int count = 0;
String str = "";
try {
Scanner scan = new Scanner(f);
while (scan.hasNextLine()) {
str = scan.nextLine().toLowerCase();
for (int i = 0; i < str.length(); i++) {
if (c == str.charAt(i)) { // Compare
count++;
}
}
}
scan.close();
System.out.println(c + " occurs " + count + " times in the file.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.