判断输入数据类型

z周威 2020-03-18 09:43:33
如果用scanner中的next () 应该怎么判断输入数字是整形还是浮点型?
...全文
113 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
dkwuxiang 2020-03-19
  • 打赏
  • 举报
回复

 Scanner s =new Scanner(System.in);
s.hasNextInt();
s.hasNextDouble();
s.hasNext() // string
天涯过客009 2020-03-19
  • 打赏
  • 举报
回复
import java.util.Scanner; import java.util.regex.Pattern; class a{ public static void main(String[] args){ System.out.println("输入一个数字"); Scanner item=new Scanner(System.in); String str=item.next(); Pattern stra = Pattern.compile("^[-\\+]?[\\d]*$"); Pattern strb = Pattern.compile("^[-\\+]?[.\\d]*$"); if(stra.matcher(str).matches()){ System.out.println("是整数"); }else if(strb.matcher(str).matches()){ System.out.println("是浮点数"); }else{ System.out.println("超出范围的数"); } } }
天涯过客009 2020-03-19
  • 打赏
  • 举报
回复
import java.util.Scanner; class Test{ public static void main(String[] args){ System.out.println("输入一个数"); Scanner tem=new Scanner(System.in); String str=tem.next(); int s=str.indexOf("."); if(s>0){ System.out.println("是浮点数"); } try{ int ss=Integer.parseInt(str); System.out.println("是整数"); }catch(NumberFormatException e){ System.out.println("不是整数"); } } }
z周威 2020-03-18
  • 打赏
  • 举报
回复
引用 1 楼 心怀啊的回复:
1,转型。2,检查是否有小数点
转型是指啥?第二种是将字符串转成数组在遍历有没有小数点吗?
心怀啊 2020-03-18
  • 打赏
  • 举报
回复
1,转型。2,检查是否有小数点

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧