2012-07-25 40 views
0

我有一个文件有两个不同的条目,其中一个来自男性,另一个来自女性。尝试读取文件并使用散列表存储,并将名称作为键和相应的ID作为值。有人能帮我弄清楚如何将它们存储在两张不同的地图上。换句话说,如果男性将它指向(map.males),并且女性将它指向(map.females)。非常感谢你。这里是示例输入和我的代码没有方向!!!!!!!使用散列图存储在两个不同的地图

**Males** 
Rob 1 
John 3 
Josh 7 
Anand 9 
Paul 5 
Norm 8 
Alex 4 

**Females** 
    Kally 43 
    Kate 54 
    Mary 23 
    Amanda 13 
    Mariam 15 
    Alyssa 18 
Christina 24 



import java.io.*; 
import java.util.*; 

class ReadFileAndStoreHashmap { 
public static void main(String[] args) { 
try{ 
    Scanner scanner = new Scanner(new FileReader("C:\")); 
    HashMap<String, String> map = new LinkedHashMap<String, String>(); 
    while (scanner.hasNextLine()) { 
    String[] columns = scanner.nextLine().split(" "); 
    if(columns.length == 2) 
    map.put(columns[0], columns[1]); 
    System.out.println(map); 
    } 
    }catch (Exception e){ 
    System.out.println(e.toString()); 
    }}} 

回答

0

如果我是正确的,你想使用两个男性和女性的地图。那么解决方案可能如下。

Scanner scanner = new Scanner(new FileReader("C:\")); 
    HashMap<String, String> males= new HashMap<String, String>(); 
    HashMap<String, String> females= new HashMap<String, String>(); 
    while (scanner.hasNextLine()) { 
    String[] columns = scanner.nextLine().split(" "); 
    if(columns.length == 2){ 
     If(its a male)      //define your logic to decide gender 
     males.put(columns[0], columns[1]); 
     else if(its a female) 
     females.put(columns[0], columns[1]); 
     else 
     //do nothing 
    } 
0

假设你有2个文件...最好是有这一个方法:

private static Map<String, String> getMap(String mapFile) throws FileNotFoundException { 

    Scanner scanner = new Scanner(new FileReader(mapFile)); 
    Map<String, String> map = new LinkedHashMap<String, String>(); 
    while (scanner.hasNextLine()) { 

     String[] columns = scanner.nextLine().trim().split(" "); 

     if (columns.length == 2) { 
      map.put(columns[0], columns[1]); 
     } 
    } 

    return map; 
} 

,并指定为需要:

Map<String, String> malesMap = getMap("map.males"); 
Map<String, String> femalesMap = getMap("map.females"); 

注意修剪()来处理领先的空白。

1

这是有点不清楚你到底在问什么。如果两者都在一个文件中,并通过女性分隔的,那么当你看到只要切换地图:

import java.io.*; 
import java.util.*; 

class ReadFileAndStoreHashmap { 
public static void main(String[] args) { 
try{ 
    Scanner scanner = new Scanner(new FileReader("C:\")); 
    HashMap<String, String> maleMap = new LinkedHashMap<String, String>(); 
    HashMap<String, String> femaleMap = new LinkedHashMap<String, String>(); 
    Map<String,String> currentMap = maleMap; 
    while (scanner.hasNextLine()) { 
    String nextLine = scanner.nextLine(); 
    if (nextLine.equals("**Females**") { 
     currentMap = femaleMap; 
    } else { 
     String[] columns = nextLine.split(" "); 
     if(columns.length == 2) { 
     currentMap.put(columns[0], columns[1]); 
    } 
    } 
    System.out.println(currentMap); 
    } 
    }catch (Exception e){ 
    System.out.println(e.toString()); 
    }}} 
+0

帮助了很多感谢..... – rob 2012-07-25 22:13:25

相关问题