永发信息网

JAVA 中 判断是不是数字 的两段 代码 有什么区别??

答案:2  悬赏:20  手机版
解决时间 2021-02-13 17:01
  • 提问者网友:不要迷恋哥
  • 2021-02-13 00:20
System.out.println("输入:");
//String num1 = sc.next();

第2个
if(sc.hasNextInt()==true)
{
int j=sc.nextInt();
}
else
{
System.out.println("输入错误!!!");
}

他们都是可以判断 是否为数字! 那他们的区别在与那里 ??
最佳答案
  • 五星知识达人网友:行雁书
  • 2021-02-13 01:12
他们在本质上是一样的,但表现不同。
第一个是先从扫描器(Scanner)中取出数据来转为String,然后使用String的match方法判断是否为数字。
由于已经取出数据了,Scanner的指向位置会+1

第二个是使用Scanner的hasNextInt()来判断下一个数据是否为数字,它并不会改变指向的位置。

为什么说他们本质上是一样的呢?
参见源代码:
Scanner:
public boolean hasNextInt(int paramInt)
{
setRadix(paramInt);
boolean bool = hasNext(integerPattern());
if (bool)
try {
String str = (this.matcher.group(this.SIMPLE_GROUP_INDEX) == null) ? processIntegerToken(this.hasNextResult) : this.hasNextResult;

this.typeCache = Integer.valueOf(Integer.parseInt(str, paramInt));
} catch (NumberFormatException localNumberFormatException) {
bool = false;
}

return bool;
}

-----------------------
String:

public boolean matches(String paramString)
{
return Pattern.matches(paramString, this);
}

可知,他们都是通过正则表达式来判断是否为整数的。

同学,你需要注意一点,如果我们有一个需求:“判断给定的字符串是否为纯数字”,我们最好使用第一个方法,不能用第二个。
在大多数情况下,Scanner并不常用。
全部回答
  • 1楼网友:山君与见山
  • 2021-02-13 02:13

第一个

import java.util.*; public class he{  public static void main(string args[]){   int zhengshu=0;   int gewei,shiwei,baiwei,he;   scanner shuru=new scanner(system.in);   system.out.println("输入一个三位数整数");   zhengshu=shuru.nextint();   while(zhengshu<100||zhengshu>999){   system.out.println("不是三位数,请重新输入");   zhengshu=shuru.nextint();   }   gewei=zhengshu%10;   shiwei=zhengshu/10%10;   baiwei=zhengshu/100;   he=gewei+shiwei+baiwei;   system.out.println("各位上的数字之和为:"+he);  } }

第二个 import java.util.*; public class he{  public static void main(string args[]){   int nian=0;   scanner shuru=new scanner(system.in);   system.out.println("请输入年号:");   nian=shuru.nextint();    while(zhengshu<100||zhengshu>999){    system.out.println("年号不能小于零,请重新输入:");     nian=shuru.nextint();   }  if(nian%4==0)  system.out.println(nian+"年是闰年。");  else system.out.println(nian+"年是平年。");

 } }

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯