拆分要输入到Map的数组

时间:2013-11-18 20:29:42

标签: java arrays string loops maps

我正在尝试拆分一组名称,例如“Joe Bloggs”Joe和Bloggs是分开的,然后可以在名字中使用第一个名称的地图。这是我到目前为止所拥有的。

public static void main(String[] args) {
    Map<String, String> snames = new HashMap<String, String>();
    int index = -1;
    String[] names = new String[8];
    Scanner s = new Scanner( System.in );
    for( int i = 0; i <= names.length; i++ ){
        System.out.println( "Enter student name:" );
        names[ i ] = s.next();
    }
    System.out.println("Please type in the student index you want to view between 0 and 7");
    index = s.nextInt();
    while (index >7 || index <0){
        System.out.println("Please type in a valid index value"); 
        index = s.nextInt();
    }
    System.out.println("The student with the index of " + index + " is " + names[index]);

    }
}

1 个答案:

答案 0 :(得分:0)

不太确定你要的是什么

for (String x : names){
    String[] temp = x.split(" "); // split "Joe Bloggs" to ["Joe", "Bloggs"]
    if (temp.length == 2){
        snames.put(temp[0], temp[1]); // Mapping "Joe" to "Bloggs"
    }
}

是你想要的吗?