Java循环和增量问题

Java循环和增量问题

本文介绍了Java循环和增量问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人可以告诉我我的程序有什么问题?

  String a [],b []; 
int c [] = new int [b.length]; (int j = 0; j for(int k = 0; k if(b [k] .equals(a [j])){
c [k] ++;
} else {
c [k] = 0;
}
}
}

我有数千个字存储在 HashMap 中。现在我想检查每个文件,从 allWords 发出多少次一个字。



你可以指出我的程序中的错误,或者给我你的想法,我该怎么做?

解决方案

您可以在阅读文件时计算单词并存储在地图上。
假设文件上的最后一个字是-1,一行中只有一个字,甚至如果这个词是生日快乐,我会做这样的事情:

  import java.util.HashMap; 
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

public class StackOverflow {

@SuppressWarnings(unchecked)
public static void main(String [] args){
扫描仪扫描器=新扫描仪(System.in);
Map< String,Integer> countWords = new HashMap< String,Integer>();
int numberOfWords = 0;
字符串字=;
while(true){
word = scanner.nextLine();
if(word.equalsIgnoreCase( - 1)){
break;
}
if(countingWords.containsKey(word)){
numberOfWords = countingWords.get(word);
countingWords.put(word,++ numberOfWords);
} else {
countingWords.put(word,1);
}
}
迭代器it = countWords.entrySet()。iterator();
while(it.hasNext()){
Map.Entry pairs =(Map.Entry)it.next();
System.out.println(pairs.getKey()+=+ pairs.getValue());
}
}
}


Can any one tell me what is the problem in my program?

String a[],b[];
int c[] = new int[b.length];

for (int j = 0; j < a.length; j++) {
    for (int k = 0; k < b.length; k++) {
        if (b[k].equals(a[j])) {
            c[k]++;
        } else {
            c[k] = 0;
        }
    }
}

I have thousands of words stored in a HashMap. Now I want to check in every file that how many time one word occurred from allWords.

Can you point out mistake in my program or give me your idea that how I can do it?

解决方案

You could count words while reading your files and store on a Map already..Assuming last word on file is "-1" and there's only one word in a line, even if the word is "happy birthday", I'd do something like this:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;

public class StackOverflow {

@SuppressWarnings("unchecked")
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    Map<String, Integer> countedWords = new HashMap<String, Integer>();
    int numberOfWords = 0;
    String word = "";
    while (true) {
        word = scanner.nextLine();
        if (word.equalsIgnoreCase("-1")) {
            break;
        }
        if (countedWords.containsKey(word)) {
            numberOfWords = countedWords.get(word);
            countedWords.put(word, ++numberOfWords);
        } else {
            countedWords.put(word, 1);
        }
    }
    Iterator it = countedWords.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
    }
}
}

这篇关于Java循环和增量问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:29