读书人

java代码小疑点

发布时间: 2012-01-08 22:48:50 作者: rapoo

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);
}

}

}

}



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


测试情况如下:

Please Enter Your Choice(An integer):
1
right
Continue ? N-not , Else--yes(An char)
yes
Please Enter Your Choice(An integer):
2
wrong
Continue ? N-not , Else--yes(An char)
yes
Please Enter Your Choice(An integer):
0
Continue ? N-not , Else--yes(An char)
N
[解决办法]
import java.io.*;

public class Test1{
public static void main(String[] args)throws Exception{
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
int in=0;
while(true){
in=Integer.parseInt(br.readLine());
switch(in){
case 1:System.out.println( "rigth ");break;
case 0:System.out.println( "wrong ");break;
default: System.out.println( "please enter 0 or 1 ");break;
}
String str=br.readLine().toLowerCase();
if(str.equals( "n "))return;
else
continue;
}
}
}
简陋了点啊,运行可以通过。。。

读书人网 >J2SE开发

热点推荐