java中的测试类_java的简单测试类

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值