检查用户输入是一个整数java

时间:2015-04-08 22:29:35

标签: 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 = ""; 
    }
  } 

4 个答案:

答案 0 :(得分:2)

"是数字"如果将字符串转换为字符数组,则可以使用的字符函数。

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;
    }
}

答案 1 :(得分:1)

如果您真的想以这种方式执行代码,建议您不要这样做

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

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

答案 2 :(得分:0)

我会使用扫描仪:

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

或者你可以去input.matches("\\d+");

答案 3 :(得分:0)

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 = ""; 
    }
  } 

应该更好。