日期:2014-05-20  浏览次数:20963 次

java代码小问题
int   choice=0   ;
BufferedReader   read   =   null   ;
while(true)
{
  BufferedReader   read   ;
  System.out.println( "Please   Enter   Your   Choice(An   integer): ")   ;
        try{
read   =   new   BufferedReader(new   InputStreamReader(System.in))   ;
choice   =   Integer.parseInt(read.readLine())   ;//第二次执行出错处
    }
    catch(NumberFormatException   e)
    {
    e.printStackTrace()   ;
    read.close()   ;
      System.exit(-1)   ;
                }
                switch(choice)
{
  case   1   :   System.out.println( "right ");     break   ;
  case   2   :   System.out.println( "wrong ");   break   ;
  default   :   break;
}
System.out.println( "Continue   ?   N-not   ,   Else--yes(An   char) ");
char   ch   =   (char)System.in.read();
if   (re   ==   'n '   ||   re   ==   'N '   ||   re   ==   '\0 ')
   {
 System.exit(0)   ;
   }
}

在执行这个程序的时候,第一次循环不会出错误,但是当第二次循环执行到从键盘读入一个整数时便报错。

------解决方案--------------------

BufferedReader read ;
  System.out.println( "Please Enter Your Choice(An integer): ") ;
try{
read = new BufferedReader(new InputStreamReader(System.in)) ;
choice = Integer.parseInt(read.readLine()) ;//第二次执行出错处
    }
    catch(NumberFormatException e)
    {
e.printStackTrace() ;
read.close() ;
System.exit(-1) ;
}

放在try外面试试!
------解决方案--------------------
if (ch == 'n ' || ch == 'N ' || ch == '\0 ')
System.exit(0);
else read.readLine();

最后你没有加read.readLine();来接受做出选择后输入的回车。

------解决方案--------------------
复制了这份代码到eclipse中,发现很多非法字符,可能是从别的地方拷贝过来的,
代码也有点乱, 我写了个同样功能的类, lz看看(可以正确运行)
import java.util.Scanner;

public class SalaryTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
int choice = 0;
Scanner read = new Scanner(System.in);
while (true) {
System.out.println( "Please Enter Your Choice(An integer): ");
try {
choice = read.nextInt();
} catch (NumberFormatException e) {
e.printStackTrace();
}

switch (choice) {
case 1:
System.out.println( "right ");
break;
case 2:
System.out.println( "wrong ");
break;
default:
break;
}
System.out.println( "Continue ? N-not , Else--yes(An char) ");
String ch = read.next();
if (ch.equals( "n ") || ch.equals( "N ") || ch.equals( "\0 ")) {
try {
read.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.exit(0);
}

}

}

}



------解决方案--------------------