1

So I'm trying to read the first 100 strings, which are words into an array of 100 Strings. and while doing that I'm trying to set each corresponding integer in an array of integers to 1, so counting each word the first time its read.

It's reading a book, 100 words at a time, and counting those words. So far I have this, how would I just make a switch statement of 100 cases?

Thanks in advance for any help!

package program6;
import java.util.Scanner;

public class Program6 {
static Scanner keyboard = new Scanner(System.in);
static String input;
String[] StringArray = new String[100];
int[] IntArray = new int[100];
String filename = "myths.txt";
String stringnumber;

public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
5
  • In other words, so far you don't have anything. Commented Dec 5, 2013 at 4:47
  • You might want to reconsider your approach to tallying word occurrences assuming that's the goal. Check out the HashMap class. Commented Dec 5, 2013 at 4:50
  • As others have pointed out, you don't need to read words in 100 at a time if you use a HashMap class. Please refer to the HashMap documentation. Commented Dec 5, 2013 at 5:20
  • Thank you for the link, we haven't learned about HashMap's yet, but I'll read up on it. Commented Dec 5, 2013 at 5:40
  • I am not saying to choose my answer, but if one of the submitted answers solved your problem, you should accept it. Also, if you found something that solved the issue yourself, you should submit a link to it as an answer and then accept it. Commented Dec 9, 2013 at 2:26

2 Answers 2

2
HashMap<String,Integer> map = new HashMap();
public void count(String file){
    Scanner in = null;
    try{
        in = new Scanner(new File(file));
    }catch(IOException ex){

    }
    String val = in.next();
    for(String currentKey : map.keySet()){
        if(map.containsKey(val)){
            map.put(currentKey,map.get(currentKey)+1);
        }else{
            map.put(val,1);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this :

Map<String, Integer> record = new HashMap<String, Integer>();
    for(String temp: StringArray){
        if(record.containsKey(temp)){
            Integer num = record.get(temp) + 1;
            record.put(temp, num);
        }
        else{
            record.put(temp, 1);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.