繁体   English   中英

检查用户输入是否为整数java

[英]check user input is an integer java

我想检查用户按下的输入是整数还是浮点数,但出现错误: incompatible operand types int and string 我正在使用处理程序,因此当用户按下返回键时,我要检查刚输入的值是数字。

void keyPressed() {
  // If the return key is pressed, save the String and clear it
  if (key == '\n' ) {
    if(input == Integer.parseInt(input)){
    saved = input;
    // A String can be cleared by setting it equal to ""
    input = ""; 
    }
  } 

如果将字符串转换为字符数组,则可以使用字符的“数字”功能。

void keyPressed() {
    // If the return key is pressed, save the String and clear it
    if (key == '\n') {
        char[] temp = input.toCharArray();
        for (char x : temp) {
            if (!Character.isDigit(x)) {
                // do something, this is not a number!
                // you can return if you don't want to save the string if it's not a number
                input = ""; // you may also want to clear the input here
                return;
            }
        }
        // other code here, such as saving the string
        saved = input;
    }
}

如果您确实想以这种方式执行代码(不建议这样做),则可以执行

if (key == '\n' ) {
   try {
      int value = Integer.parseInt(input)
      // Is an integer
   } catch (NumberFormatException e) {
      // Not an integer
   }
} 

正确的方法是检查字符串中每个字符的char并确保每个数字都是数字。

我会使用扫描仪:

Scanner sc = new Scanner(input);
if(!sc.hasNextInt()) return false;
sc.nextInt();
return !sc.hasNext(); // should be done

或者您可以只input.matches("\\\\d+");

Integer.parseInt(input)将输入转换为int,然后检查String == int。

void keyPressed() {
    if (key == '\n' ) {
        try {
            Integer.parseInt(input);
            saved = input;
        }
        catch(NumberFormatException e){
            //ignore input
        }
    // A String can be cleared by setting it equal to ""
    input = ""; 
    }
  } 

应该更好地工作。

暂无
暂无

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

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