// 5. 设计一个程序,其功能是从命令行输入浮点数数字符串,再将该整数字符串转换为整数,输入的数据可能具有以下格式:
// 123.45
// 123. 45
// 123x yz4.56
// 对可能会发生异常进行捕获和处理。
//之前的尝试代码
// import java.util.*;
// //导入java的一个基础库(util)的全部类
// public class test104{
// public static void main(String args[]){
// Scanner scanner = new Scanner(System.in);//读取用户输入的字符串
// System.out.print("请输入一个浮点数字符串:");
// String input = scanner.nextLine();//读取输入的下一行
// try {
// double num = Double.parseDouble(input);//将字符串转变为double类型
// int integer = (int) num;
// System.out.println("转换后的整数为:" + integer);
// } catch (NumberFormatException e) {//用于捕捉用户所写的浮点型字符串是否发生了异常
// System.out.println("输入的字符串不是一个合法的浮点数!");
// }
// /*java.lang.NumberFormatException 数字格式异常。当试图将一个String转换为指定的数字类型,而该字符串确不满足数字类型要求的格式时,抛出该异常. */
// }
// }
import java.util.*;//调用其中的全部类
class inputException extends Exception{//继承异常类
inputException(){
super();//调用父类构造函数
}
inputException(String str){
super(str);//注意该句话要放在第一行
}
}//自定义异常
public class test104{
static double test(String str1)throws inputException{//定义函数
if(str1.contains(" ")){
throw new inputException("输入不能带空格,发生错误");
}//抛出第一种异常
for(int i=0;i<str1.length();i++){//length()返回长度
if((int)str1.charAt(i)>=65){//charAt()如果给定的索引号大于或等于此字符串长度或负数,则返回 StringIndexOutOfBoundsException
throw new inputException("输入不能带有字母,发生错误");
}//抛出第二种异常
}
return Float.parseFloat(str1) ;//返回浮点
}
public static void main(String[]args)throws inputException{
System.out.println("输入字符串:");
Scanner input=new Scanner(System.in);
String str1=input.nextLine();
double lu=test(str1);
System.out.println(lu);//输出结果
}
}
11-11
1328
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交