java中的输入总是伴随着异常(这是我的个人见解),所以,用下面这个简单类,就简化了每次都要抛异常的问题。



import java.io.*;
public class Console
{
 /**Reads a single double from the keyboard. Stops execution in case of error.
 @return double*/
 public static double readDouble()
 {
  try
  {
   return Double.valueOf(readString().trim()).doubleValue();
  }catch(NumberFormatException ne)
  {
   System.err.println("Console.readDouble:Not a double...");
   System.exit(-1);
   return 0.0;
  }
 }
 /**Reads a single int from the keyboard. Stops execution in case of error.
 @return int */
 public static int readInt()
 {
  try
  {
   return Integer.valueOf(readString().trim()).intValue();
  }catch(NumberFormatException ne)
  {
   System.err.println("Console.readInt:Not aninteger...");
   System.exit(-1);
   return -1;
  }
 }
 /**Reads a String from the keyboard until RERUEN or ENTER key is pressed.
 @return String */
 public static String readString()
 {
  String string =new String();
  BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
  try
  {
   string=in.readLine();
  }catch(IOException e)
  {
   System.out.println("Console.readString:Unknown error...");
   System.exit(-1);
  }
  return string;
 }
}



测试代码:



/**test the Console.java
@author icecold */
public class ConsoleTest
{
	public static void main(String[] args)
	{
		System.out.print("Enter integer: ");
		int i=Console.readInt();
		System.out.print("Enter double: ");
		double d=Console.readDouble();
		System.out.println("Integer enered: "+i);
		System.out.println("Double entered: "+d);
		double x=i+d;
		System.out.println(x);
	}
}