[英]Java storing the inputs from scanner
當我無法使用“列表”,但需要存儲掃描儀的輸入時,該如何處理?
我想讓程序計算掃描儀輸入中出現的輸入頻率。
例如,如果輸入是
“我喜歡蘋果,但我也喜歡香蕉”
結果是
我:2喜歡:2蘋果:1香蕉:1但是:1也是:1
起初,我想到了制作字符串數組的方法,每次輸入輸入內容時,我都會將它們放入數組中。 之后,盡管這將需要n ^ 2的時間復雜度,但是請為每個元素運行for循環,然后檢查其是否具有相同的單詞。
for (String str in arr){
for(String str_2 in arr){
if(strr.equals(str_2)){
count[i]++;
} // count is the array storing the frequencies.
但是這里的問題是...在聲明arr時,我應該知道輸入大小。 其他人告訴我使用“列表”,但是“列表”的使用受到限制。
在這種情況下,應該怎么辦?
可以使用Java 流嗎?
String[] array = {"i", "like", "apple", "but", "i", "like", "banana", "too"};
或從用戶那里獲取輸入,例如:
Scanner sc = new Scanner(System.in);
int numberOfEntries = sc.nextInt(); // defines how big the array should be
String[] array = new String[numberOfEntries];
for (int i = 0; i < numberOfEntries; i++) {
System.out.println("Enter value " + (i+1));
String word = sc.next();
array[i] = word;
}
Arrays.stream(array).collect(Collectors.groupingBy(p -> p, Collectors.counting()))
.entrySet().stream().forEach(key -> System.out.println(key.getKey() + ": " + key.getValue()));
輸出:
香蕉:1
但是:1
蘋果:1
太:1
喜歡:2
我:2
您可以通過使用HashMap並在for循環中遍歷輸入數組並檢查映射是否已包含鍵來執行類似的操作。 如果包含,則只需增加值的計數即可。 如果鍵尚未在地圖中,則只需將其與值1相加即可。
for (String str : inputArray) {
if (map.containsKey(str)) {
map.put(str, map.get(str) + 1);
} else {
map.put(str, 1);
}
}
最后,只需遍歷地圖並使用鍵和值對進行打印。
String input = "I like apple but I like banana too";
String[] words = input.split(" ");
int countfre=0;
HashMap<String,Integer> map = new HashMap<String, Integer>();
for(int i=0;i<words.length;i++){
if(!map.containsKey(words[i])){
for (int j=0;j<words.length;j++){
if(words[i].equalsIgnoreCase(words[j])){
countfre++;
}
map.put(words[i],countfre);
}
countfre=0;
System.out.println(words[i] + " = " +map.get(words[i]));
}
}
//沒有Java流api。 //將輸出存儲在Map中。
輸出:
香蕉= 1
但= 1
蘋果= 1
太= 1
喜歡= 2
我= 2
嘗試類似的東西,
public static void main(String[] args) {
//input
String s = "I like apple but I like banana too";
//desired output
//I: 2 like: 2 apple: 1 banana: 1 but: 1 too: 1
String[] str = s.split(" ");
String[] result = new String[str.length];
int temp = 0;
test:
for (String str1 : str) {
for (String str2 : result) {
if(str1.equals(str2)){
continue test;
}
}
result[temp++] = str1;
int count = 0;
for (String str2 : str) {
if(str1.equals(str2)){
count++;
}
}
System.out.print(str1 + ": " + count + " ");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.