|
查看: 1091|回复: 3
|
Java hashMap 问题 [已解决]
[复制链接]
|
|
|
嘿又麻烦各位,有问题请教了。
已下program是要create 一个 phoneBook,记录名字和电话。
要用hashMap,然后写进 txt 文件。使用" : " 做separator.
问题出在我把资料写进了之后,却没有办法利用separator读到资料。
而separator的数值一直是 -1 的。。。
为什么啊。。。??? 请指教,谢谢
import java.util.*;
import java.io.*;
import java.lang.*;
public class hashMap
{
static HashMap<String,Integer> pBook = new HashMap<String,Integer>();
static Scanner scan2Book = new Scanner(System.in);
static File f = new File("phoneBook.txt" );
public void addMap() throws IOException, ClassNotFoundException
{
String nameKey;
int numValue;
System.out.println("Enter name:" );
nameKey = scan2Book.nextLine();
System.out.println("Enter number:" );
numValue = scan2Book.nextInt();
pBook.put(nameKey, numValue);
Set set = pBook.entrySet();
Iterator i = set.iterator();
Map.Entry me = (Map.Entry)i.next();
//System.out.println(pBook);
System.out.println(me.getKey() + " : " + me.getValue());
FileWriter fos = new FileWriter(f);
PrintWriter dos = new PrintWriter(fos);
dos.write(nameKey+" : "+numValue);
//dos.newLine();
dos.close();
}
public void searchMap() throws IOException, ClassNotFoundException
{
String nameKey;
System.out.println("Enter name:" );
nameKey = scan2Book.nextLine();
}
public static void main(String[] args) throws IOException, ClassNotFoundException
{
if(!f.exists())
{
System.out.println("No data file found.A new data file will be created for you!!" );
System.out.println("The new data file name is: " + f.getAbsolutePath());
}
else
{
Scanner sf = new Scanner("phoneBook.txt" );
while(sf.hasNextLine())
{
String scanLeBook = sf.nextLine();
//问题在这里!
int seperator = scanLeBook.indexOf(" : " );
if (seperator == -1)
{
throw new IOException("The file contains irrelevant data!" );
}
String nameKey = scanLeBook.substring(0, seperator);
String numOfValue = scanLeBook.substring(seperator+3);
int numValue = Integer.parseInt(numOfValue);
pBook.put(nameKey,numValue);
}
}
Scanner sc = new Scanner(System.in);
hashMap addPbook = new hashMap();
System.out.println("1-Add, 2-Search, 3-Exit" );
String select = sc.nextLine();
if(select.equals("1" ) == true)
{
addPbook.addMap();
}
else if(select.equals("2" ) == true)
{
addPbook.searchMap();
}
else
{
System.out.println("wahahahaha" );
}
}
}
这次 已尽量 modularize 了。
[ 本帖最后由 nick_khor 于 11-8-2009 12:37 PM 编辑 ] |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 11-8-2009 01:49 AM
|
显示全部楼层
|
|
|
|
|
|
|
|
|
|
发表于 11-8-2009 12:15 PM
|
显示全部楼层
String scanLeBook = sf.nextLine();
scanLeBook 你拿到的 RESULT = phoneBook.txt , 你找 “:” 當然會RESULT - 1 |
|
|
|
|
|
|
|
|
|
|

楼主 |
发表于 11-8-2009 12:19 PM
|
显示全部楼层
|
|
|
|
|
|
|
|
| |
本周最热论坛帖子
|