求java程序;编程求解并输出从键盘输入的浮点数的平方根,并设计自己的异常类处理输入数据小于0

2025-04-02 19:26:41
推荐回答(2个)
回答1:

import
.BufferedReader;
import
.IOException;
import
.InputStreamReader;

public class TestFloat
{
public static void main(String[] args)
{
System.out.println("请输入一个数:");
double input = 0;
boolean flag=true;
while(flag)
{
try{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
input=Double.valueOf(in.readLine());
if(input<0)
{
System.out.println("输入的是负数!");
}
else
flag=false;
}
catch(NumberFormatException e)
{
System.out.println("输入格式有误!请重新输入!");

}catch(IOException e)
{
e.printStackTrace();
}
}
System.out.println("输入的数为:"+input);
System.out.println(input+"的
为:"+Math.sqrt(input
));

}
}

回答2:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestIn {
public static void main(String[] args) throws IOException {
System.out.println("请输入整数或小数");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String str = stdin.readLine();
try {
double in = Double.parseDouble(str);
if(in<0){
System.out.println("输入了负数");
}
System.out.println(str+"的平方根为:"+Math.sqrt(in));
} catch (Exception e) {
System.out.println("输入的数据不能包含字母");
}
}
}