简体   繁体   English

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

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

I wrote a simple program that calculates the hypotenuse of a triangle when the user inputs side A and B. I have a while loop that prompts the user to enter a value greater than 0 if they do, but how do I check if the user enters a String value? 我编写了一个简单的程序,当用户输入A侧和B侧时计算三角形的斜边。我有一个while循环,提示用户输入大于0的值,但是如何检查用户是否输入字符串值?

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

What should I add so if the user enters a string value, the loop will also start? 我应该添加什么,以便如果用户输入字符串值,循环也将开始?

Thanks 谢谢

However you get your input (from command line, scanner or buffered reader) first parse it and try to store it in an integer variable. 但是,您首先从命令行,扫描仪或缓冲读取器中获取输入,然后将其解析并尝试将其存储在整数变量中。 If its a string, then catch the exception and allow the user to enter the value again. 如果它是字符串,则捕获异常并允许用户再次输入该值。

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!");
  }     

you can use the binary instanceof operator. 您可以使用二进制instanceof运算符。 it returns a boolean value in this manner: 它以这种方式返回布尔值:

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

This approach can of course be used to check for other types as well. 当然,这种方法也可以用于检查其他类型。 I recommend type checking your A and B variables as strings using instanceof and handle accordingly 我建议使用instanceof将A和B变量作为字符串进行类型检查,并进行相应处理

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

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