设计一个程序,其功能是从命令行输入浮点数数字符串,再将该整数字符串转换为整数,输入的数据可能具有以下格式: 123.45 123. 45 123x yz4.【个人复盘】

// 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);//输出结果

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值