Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
Why doesn't the HashMap print after loading ArrayList values into it?

I am attempting to write a program for school that counts the frequency of tokens (words in this case) in a given file. The driver program should use a list structure to get each word in the same format from the file. Then, a FreqCount object is created and will eventually use the hashmap to count token frequency. I got the driver to read the file and get it into an ArrayList, but now the issue is either (a) the code to input the list is not working, so it is empty (b) the print function is not working properly (unlikely since I ripped it straight off of w3schools to test). I have thought about this for a while and can't figure out why it won't work.

Driver:

package threetenProg3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import threetenProg3.FreqCount;

public class Driver {
    
    public static void main(String[] args) throws FileNotFoundException{
        File in = new File("test.txt");
        Scanner scanFile = new Scanner(in);
        
        ArrayList<String> parsed = new ArrayList<String>();
        FreqCount fc = new FreqCount(parsed);
        
        while(scanFile.hasNext()) { //if this ends up cutting off bottom line, make it a do while loop
            parsed.add(scanFile.next().toLowerCase());
        }

        System.out.println("ArrayList: \n");
        
        for(int i = parsed.size()-1; i>=0; i--) { //prints arraylist backwards
            System.out.println(parsed.get(i));
        }
        
        System.out.println("\n Hashmap: \n");
        fc.printMap();

        scanFile.close();
    }
}

FreqCount:

package threetenProg3;

import java.util.HashMap;
import java.util.ArrayList;

public class FreqCount {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    
    FreqCount(ArrayList<String> plist){
        for(int i = plist.size()-1; i>=0; i--) { //puts list into hashmap
            map.put(plist.get(i), 1);
        }
    }
    
    //methods
    
    public void printMap() {
        for (String i : map.keySet()) {
              System.out.println("key: " + i + " value: " + map.get(i));
        }
    }
    
}

The only thing I could think of was changing the List to an ArrayList, but that had no effect.

Edit: I realized I forgot a bunch of important stuff here.

Text file:

ONE TWO ThReE FoUR fIve
six     seven        
EIGHT
     NINE       
TEN ELEVEN

which outputs:

eleven
ten
nine
eight
seven
six
five
four
three
two
one

When printing the arraylist, it works perfectly. The issue is when it comes to printing the hashmap. Currently, the output for printing the hashmap is blank (as in nothing shows up after "Hashmap: ".

Thanks to anyone who can help, quick feedback is greatly appreciated :)

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

you have to create a frequency counter after reading the list because you are inserting values into the map in the constructor. And since the list is still empty when you created the FreqCount you don't see any output.

package threetenProg3;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import threetenProg3.FreqCount;

public class Driver {
    
    public static void main(String[] args) throws FileNotFoundException{
        File in = new File("test.txt");
        Scanner scanFile = new Scanner(in);
        
        ArrayList<String> parsed = new ArrayList<String>();
        
        while(scanFile.hasNext()) { //if this ends up cutting off bottom line, make it a do while loop
            parsed.add(scanFile.next().toLowerCase());
        }

        System.out.println("ArrayList: \n");
        
        for(int i = parsed.size()-1; i>=0; i--) { //prints arraylist backwards
            System.out.println(parsed.get(i));
        }
        
        System.out.println("\n Hashmap: \n");
        FreqCount fc = new FreqCount(parsed); // Moved fc here
        fc.printMap();

        scanFile.close();
    }
}
over 4 years ago · Santiago Trujillo Relatório

0

This line:

FreqCount fc = new FreqCount(parsed);

does not magically "bind" the array list parsed to the map. It just adds what's currently in parsed into fc.map. If you examine your code, you'll see that parsed is empty at the time the above line executes. So you are adding nothing to the map.

You should move that line to after you have added to the array list. For example, just before you print "Hashmap:":

FreqCount fc = new FreqCount(parsed);
System.out.println("\n Hashmap: \n");
fc.printMap();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda