14 Replies - 894 Views - Last Post: 26 September 2014 - 09:39 AM Rate Topic: -----

#1 ricososwavay  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 113
  • Joined: 11-February 14

How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 08:17 AM

I have a file called statecapitals.txt that is read in, I want to store it in either a 2d array or hashmap and select a random state then Ask the user for the name of the capital. Then I want to Let them know if they are correct or not and have a choice to play as many times as they like. When they no longer want to play,I want to let them know how many they got correct and how many incorrect. I am not sure which would be better a hash map or 2d array and dont know where to start with each.

here is what the text file looks like:
Alabama - Montgomery
Alaska - Juneau
Arizona - Phoenix
Arkansas - Little Rock
California - Sacramento
Colorado - Denver
Connecticut - Hartford
Delaware - Dover
Florida - Tallahassee
Georgia - Atlanta
Hawaii - Honolulu
Idaho - Boise
Illinois - Springfield
Indiana - Indianapolis
Iowa - Des Moines
Kansas - Topeka
Kentucky - Frankfort
Louisiana - Baton Rouge
Maine - Augusta
Maryland - Annapolis
Massachusetts - Boston
Michigan - Lansing
Minnesota - St. Paul
Mississippi - Jackson
Missouri - Jefferson City
Montana - Helena
Nebraska - Lincoln
Nevada - Carson City
New Hampshire - Concord
New Jersey - Trenton
New Mexico - Santa Fe
New York - Albany
North Carolina - Raleigh
North Dakota - Bismarck
Ohio - Columbus
Oklahoma - Oklahoma City
Oregon - Salem
Pennsylvania - Harrisburg
Rhode Island - Providence
South Carolina - Columbia
South Dakota - Pierre
Tennessee - Nashville
Texas - Austin
Utah - Salt Lake City
Vermont - Montpelier
Virginia - Richmond
Washington - Olympia
West Virginia - Charleston
Wisconsin - Madison
Wyoming - Cheyenne

Is This A Good Question/Topic? 0
  • +

Replies To: How to store a file in a hashmap or 2d array ? Which is better?

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3540
  • View blog
  • Posts: 16,130
  • Joined: 20-September 08

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 08:30 AM

A Map<String, String> would be best
Was This Post Helpful? 1
  • +
  • -

#3 ricososwavay  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 113
  • Joined: 11-February 14

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 08:51 AM

Ok thank you so here is my code so far, I still need to select a random capital from the hashmap and display to user and ask the user enter the capital and check to see if correct or incorrect .Sorry I am a newbie in java.

public static void main(String[] args) {

// Location of file to read
File file = new File("statecapitals.txt");

try {

Scanner scanner = new Scanner(file);
String[] values;
Map<String, String> map = new LinkedHashMap<String, String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
values = line.split("-");
String state = values[0];
String capital = values[1];
map.put(state, capital);

System.out.println(state);

}

scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}
Was This Post Helpful? 0
  • +
  • -

#4 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3540
  • View blog
  • Posts: 16,130
  • Joined: 20-September 08

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 09:14 AM

Don't pile code into main. That's the code to read the file and fill the map, so that should be just one method of your class
Was This Post Helpful? 1
  • +
  • -

#5 ricososwavay  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 113
  • Joined: 11-February 14

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 09:31 AM

Ok I have fixed that but still no answer on how to select a random capital from the hashmap and display to user and ask the user enter the capital and check to see if correct or incorrect
Was This Post Helpful? 0
  • +
  • -

#6 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3540
  • View blog
  • Posts: 16,130
  • Joined: 20-September 08

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 09:37 AM

You can simplify your map fill:

        try {
            Scanner scanner = new Scanner(file);
	    scanner.useDelimiter(" - |[\r\n]");
            Map<String, String> map = new LinkedHashMap<String, String>();
            while (scanner.hasNext()) {
                map.put(scanner.next(), scanner.next());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }



You can create a list of entries from the map and select at random
Was This Post Helpful? 0
  • +
  • -

#7 ricososwavay  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 113
  • Joined: 11-February 14

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 09:59 AM

Sorry but i am a newbie at java and basically need some sort of example code. I dont even know where to start.
Was This Post Helpful? 0
  • +
  • -

#8 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3540
  • View blog
  • Posts: 16,130
  • Joined: 20-September 08

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 10:17 AM

	List<Map.Entry<String, String>> entryList = new ArrayList<>(map.entrySet());
	Map.Entry<String, String> randomEntry = entryList.get((int)(Math.random() * entryList.size()));


Will get you a random entry. Since that list is immutable (as is the map), you can store it as an instance variable and reuse it
Was This Post Helpful? 0
  • +
  • -

#9 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1576
  • View blog
  • Posts: 3,548
  • Joined: 05-April 11

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 25 September 2014 - 10:21 AM

I would not be using a 2D array or hashmap
Instead a regular 1D array or list with a State object would do
Representing the capital concept as an object is probably a good idea too.. if you want to expand later on
ArrayList<State> states = new ArrayList<State>();
//TODO Populate states from file

public class State {
    private Capital capital;
    //...
}

public class Capital {
    private String name;
    //...
}


Loading content from the file might as well be moved into its own object
It could somehow fit into a StateList class which extends one of the list implementations (ArrayList?)
public class StateList extends ArrayList<State> {
	
	public void loadFromFile(String filename) throws IOException {
		//TODO
	}
}


Was This Post Helpful? 0
  • +
  • -

#10 ricososwavay  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 113
  • Joined: 11-February 14

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 26 September 2014 - 06:43 AM

I am reading in a file that stores the states and state capitals. I then put them into a hashmap. I then stored the keys into a list and select a random key. The problem I am having is that I want to get a random state so I can then ask the user what the capital of the state is and check if correct or incorrect till the user wants to stop playing. Currently my code is selecting a random capital instead of state. I need coded examples only please as I am a newb to java and I lear better studying the code. Thanks.

try {
 
            Scanner scanner = new Scanner(file);
            String[] values; 
            Map<String, String> map = new HashMap<String, String>();   
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                values = line.split("-");  
                String state = values[0];  
                String capital = values[1];    
                map.put(state, capital);
                
                
            }
            scanner.close();
            List<String> keysAsArray = new ArrayList<String>(map.keySet());
                Random r = new Random();
                System.out.println(map.get(keysAsArray.get(r.nextInt(keysAsArray.size()))));
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


Was This Post Helpful? 0
  • +
  • -

#11 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1576
  • View blog
  • Posts: 3,548
  • Joined: 05-April 11

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 26 September 2014 - 07:02 AM

Merged topics. Please don't start a new topic for every question you might have about the task
Was This Post Helpful? 0
  • +
  • -

#12 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3540
  • View blog
  • Posts: 16,130
  • Joined: 20-September 08

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 26 September 2014 - 07:22 AM

I've already answered the question of getting a random entry

I think on reflection, that CasiOo's suggestion about the OO modelling is probably a better approach though
Was This Post Helpful? 0
  • +
  • -

#13 ricososwavay  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 113
  • Joined: 11-February 14

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 26 September 2014 - 07:30 AM

@goose that code gets me both values, I want to display a state then ask the user what the capital is then check to see if it matches. the requirements are to use a map also.

This post has been edited by ricososwavay: 26 September 2014 - 07:32 AM

Was This Post Helpful? 0
  • +
  • -

#14 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3540
  • View blog
  • Posts: 16,130
  • Joined: 20-September 08

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 26 September 2014 - 07:34 AM

Quote

@casioo that code gets me both values
Do you mean '@casioo'? What gets you both values?

Well if you take the trouble to look at the API docs for Map.Entry, you'll see it's simplicity itself to get the key and the value and just show the user the former. Quite apart from that, how would having just one piece of data be of any use to you?

This post has been edited by g00se: 26 September 2014 - 07:36 AM
Reason for edit:: typo

Was This Post Helpful? 0
  • +
  • -

#15 ricososwavay  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 113
  • Joined: 11-February 14

Re: How to store a file in a hashmap or 2d array ? Which is better?

Posted 26 September 2014 - 09:39 AM

I have updated code but when i enter the capital for the state even if correct it is saying it is incorrect, it is not matching with the value(capital) for the key(state)..

Updated code:

public class StateCapitals {
    Scanner in;

    public static void main(String[] args) {
        readData();
            
    }
 
    public static void readData() {    // Location of file to read
        File file = new File("statecapitals.txt");
        
        try {
 
            Scanner scanner = new Scanner(file);
            String[] values;

            Map<String, String> map = new HashMap<String, String>();   
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                values = line.split("-");  
                String state = values[0];  
                String capital = values[1];    
                map.put(state, capital);   
            }
            scanner.close();
            Scanner scan = new Scanner(System.in);
            boolean again=true;
            int correct=0;
            int incorrect=0;
            while(again){
                List<String> keysAsArray = new ArrayList<String>(map.keySet());
                Random r = new Random();
               
                String randomstate = keysAsArray.get(r.nextInt(keysAsArray.size()));
                System.out.println("What is the capital of " + randomstate);
                String capital=scan.nextLine();
                if(capital.equals(map.get(randomstate))){
                    correct++;
                    System.out.println("Correct");    
                        }
                else{
                    incorrect++;
                    System.out.println("Inorrect");
                }
                
            System.out.println("Another State? Enter true/false");
            again = Boolean.parseBoolean(scan.nextLine());
                
                
            }
            System.out.println("Correct: " + correct +"\nIncorrect: " + incorrect);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
  
    }
 
            
}



This post has been edited by ricososwavay: 26 September 2014 - 09:40 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1