Java程序问题,请问下面的程序编译可以通过,但是运行到输入价格后,就不进行了。怎么回事?
import java.util.*;
public class Caidan {
public static void main(String args[])throws IOException{
Map<String ,String > map=new HashMap<String,String>();
ObjectOutputStream bot=new ObjectOutputStream(new FileOutputStream("c:/newlist.txt"));
boolean b=true;
inner:
while(b){
System.out.println("添加新菜:");
Scanner cname=new Scanner(System.in);
String c=cname.next();
System.out.println("添加价格:");
String a=cname.next();
map.put(c,a);
System.out.println("是否继续添加:是1,退出0");
outter:
while(true){
int n=cname.nextInt();
if(n==1)continue inner;
else if(n==0){b=false;continue inner;}
else{System.out.println("输入有误:");continue outter;}
}
}
Set<String> set = map.keySet();
for (Iterator<String> i = set.iterator(); i.hasNext();) {
bot.writeBytes(map.get(i.next()));
}
}
} 展开
程序本身没大错,就是scanner每次都new一个有点设计上的问题,改的版本在下面,有注释
运行结果:
package learn;
import java.io.*;
import java.util.*;
public class Other {
public static void main(String args[]) throws IOException {
Map<String, String> map = new HashMap<String, String>();
//我不理解为什么下面要用ObjectOutputStream?OutputStreamWriter/FileWriter无法满足你的要求?
//ObjectOutputStream顾名思义是写出对象的,你可以直接用它吧上面那个map写到文件里
//不过写出来的结果你可能看不懂,二进制的
//最后再用ObjectInputStream读入就可以了
//推荐你去查下java.io的api
OutputStreamWriter bot = new OutputStreamWriter(new FileOutputStream("newlist.txt"));//位置在当前文件夹下,我的习惯,可以不改,无意义
Scanner cname = new Scanner(System.in); //每次循环都要新建一个scanner?我认为只要最初有一个就够用了
while (true) {
System.out.println("添加新菜:");
String c = cname.next();
System.out.println("添加价格:");
String a = cname.next();
map.put(c, a);
System.out.println("是否继续添加:是1,退出0");
int n = cname.nextInt();
if (n != 1) { //查一下while的基本用法,可以简化很多语句
break;
}
}
Set<String> set = map.keySet();
for (Iterator<String> i = set.iterator(); i.hasNext();) {
bot.write(map.get(i.next()));
}
//没有这两句你的文件里很有可能啥都没有,如果你有意或者无意使用了BufferedOutputStream,、
//另外关闭流是个好习惯
bot.flush();
bot.close();
System.out.println("finish");
}
}
import java.io.*;
import java.util.*;
public class Caidan
{
public static void main(String args[])
throws IOException
{
Map<String, String> map = new HashMap<String,String>();
ObjectOutputStream bot = new ObjectOutputStream(new FileOutputStream("c:/newlist.txt"));
boolean b = true;
inner:
while(b)
{
System.out.println("添加新菜:");
Scanner cname = new Scanner(System.in).useDelimiter("\\n");;
String c = cname.next();
System.out.println("添加价格:");
String a = cname.next();
map.put(c, a);
System.out.println("是否继续添加:是1,退出0");
outter:
while(true)
{
cname.reset();
int n = cname.nextInt();
if(n == 1)
continue inner;
else if(n == 0)
{
b = false;
continue inner;
}
else
{
System.out.println("输入有误:");
continue outter;
}
}
}
Set<String> set = map.keySet();
for(Iterator<String> i = set.iterator(); i.hasNext();)
{
bot.writeBytes(map.get(i.next()));
}
}
}
2011-05-16