有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当用户按下“回车”键或空格键时,会弹出错误消息

我想在用户按enter或空格enter而不是字符串时打印一条错误消息。我尝试了isEquals(“”)和isEmpty(),但还没有找到任何有效的方法

这是我的密码:

import java.util.Scanner;

public class check{
    public static void main(String args[]){
      System.out.println("Enter a number: ");
      Scanner keyboard = new Scanner(System.in);
      String input = keyboard.next();

      if(input.equals("")){
        System.out.println("Empty");
      } else {
        System.out.println("number inputed");
    }
  }

}


共 (5) 个答案

  1. # 1 楼答案

    import java.util.Scanner;
    
    public class check{
        public static void main(String args[]){
          System.out.println("Enter a number: ");
          Scanner keyboard = new Scanner(System.in);
          String input = keyboard.nextLine();
    
    
          if(input.trim().equals("")){
            System.out.println("Empty");
          } else {
            System.out.println("number inputed");
        }
      }
    }
    
  2. # 2 楼答案

    一种方法是,将keyboard.next()更改为keyboard.nextLine(),使用trim()删除不必要的空格,使用isEmpty()检查

    String input = keyboard.nextLine().trim();
    if (input.isEmpty()) {
        // error message
    } else {
        // good to go
    }
    
  3. # 3 楼答案

    要检查字符串输入是否为空,可以使用String.isEmpty()方法。请看下面:

    String input = keyboard.nextLine();
    if(!input.isEmpty()) {
      //the input is not empty! 
    } 
    else {
      //the input is empty! 
    } 
    

    但是,请注意,由于您希望接收数字作为输入,因此不应将其作为字符串检索。下面是程序从用户检索double的示例^{}提供了许多方法来验证用户的输入。在本例中,我使用hasNextDouble()检查输入是否为数字

    Scanner scanner = new Scanner(System.in); 
    System.out.println("Enter a number:");
    
    while(!scanner.hasNextDouble()) {
      System.out.println("That's not a number!");
      scanner.next();
    } 
    
    double numberInput = scanner.nextDouble();
    System.out.println("The entered number was " + numberInput);
    
  4. # 4 楼答案

    我制作了一个与您类似的示例程序,并使用nextLine()而不是next()。当用户输入空格并单击enter时,他将打印“空格”或“数字”

    enter image description here

  5. # 5 楼答案

    奇怪的是,我在运行代码时没有遇到错误。但是,我注意到您的代码对空输入没有反应(只需按enter键)。若你们想检查,你们可以使用键盘。nextLine()

    从代码的其余部分来看,您似乎只希望用户输入一个数字。如果您正在使用扫描仪,检查用户是否输入了整数的一个简单方法是键盘。hasNextInt()

    意思是你可以这样做:

    if(keyboard.hasNextInt()) {
      int yourNumber = keyboard.nextInt();
      System.out.println("Your number is: " + your Number);
    }
    else {
      System.out.println("Please enter a valid integer");
    }