繁体   English   中英

您如何检查用户输入的是字符串值而不是数字?

[英]How do you check that the user entered a String value instead of a number?

我编写了一个简单的程序,当用户输入A侧和B侧时计算三角形的斜边。我有一个while循环,提示用户输入大于0的值,但是如何检查用户是否输入字符串值?

while (sideA<=0 || sideB<=0) {

我应该添加什么,以便如果用户输入字符串值,循环也将开始?

谢谢

但是,您首先从命令行,扫描仪或缓冲读取器中获取输入,然后将其解析并尝试将其存储在整数变量中。 如果它是字符串,则捕获异常并允许用户再次输入该值。

try 
{
   int sideA = Integer.parseInt(input);
} 
catch (NumberFormatException ex) 
{
  //Do something here to keep continuing the while loop

}
  Scanner input = new Scanner(System.in);

  // requesting user input
  System.out.println("Enter x and y : ");

  String x = input.next();
  String y = input.next();

  try {
     double d1 = Double.parseDouble(s1);
     double d2 = Double.parseDouble(s2);

     if(d1 > 0 && d2 > 0) {
        //Call for the hypotenuse method
        double z = hypotenuse(d1,d2);
     }
  } catch (NumberFormatException e) {
        System.out.println("Invalid Input!");
  }     

您可以使用二进制instanceof运算符。 它以这种方式返回布尔值:

if( myVariable instanceof String )
    //it's a string!
else
    //it's not a string

当然,这种方法也可以用于检查其他类型。 我建议使用instanceof将A和B变量作为字符串进行类型检查,并进行相应处理

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM