【问题标题】:How to get the user input in Java?如何在 Java 中获取用户输入?
【发布时间】:2011-07-14 08:07:32
【问题描述】:

我试图创建一个计算器,但我无法让它工作,因为我不知道如何获取用户输入

如何在 Java 中获取用户输入?

【问题讨论】:

  • 呃,你的问题是什么?您刚刚发布了一些代码并说您不喜欢指针。如果您不了解按引用传递和按值传递,不了解指针仍然会在 java 中反噬您。
  • 你应该尝试学习java 读一本书,Java How to Program,7/e 不错

标签: java input


【解决方案1】:

最简单的方法之一是使用Scanner 对象,如下所示:

import java.util.Scanner;

Scanner reader = new Scanner(System.in);  // Reading from System.in
System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.
//once finished
reader.close();

【讨论】:

  • 如果关闭打开到 System.in 的 Scanner 对象,您将无法重新打开 System.in,直到程序完成。
  • @ksnortum 我可以通过Scanner reader1 = new Scanner(System.in);重新打开吗?
  • 试试看。我不这么认为。
  • 是的,ksnortum 是对的,你得到了 NoSuchElementException。关于why you cannot reopen System.in after closing it的一些有用的相关问题。
【解决方案2】:

您可以根据要求使用以下任何选项。

Scanner

import java.util.Scanner; 
//...
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReaderInputStreamReader

import java.io.BufferedReader;
import java.io.InputStreamReader;
//...
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(s);

DataInputStream

import java.io.DataInputStream;
//...
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

DataInputStream 类中的readLine 方法已弃用。要获取 String 值,您应该使用以前的解决方案与 BufferedReader


Console
import java.io.Console;
//...
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

显然,这种方法在某些 IDE 中效果不佳。

【讨论】:

  • 请注意,DataInputStream 用于读取二进制数据。在System.in 上使用readInt 不会从字符数据中解析整数,而是会重新解释unicode 值并返回无意义的值。详情见DataInput#readIntDataInputStream实现DataInput)。
  • 这太棒了,希望看到为完整性添加所需的导入。它也将真正帮助那些需要它的人。
  • 如果它提到了实际的要求,这个答案会更有帮助。我已经开始悬赏尝试解决这个问题。
【解决方案3】:

您可以使用Scanner 类或控制台类

Console console = System.console();
String input = console.readLine("Enter input:");

【讨论】:

  • 我认为如果此代码从 Eclipse 运行,System.console 将返回 null。
  • 我相信这将返回从几乎任何 IDE 运行的错误。确认 IntelliJ 也有同样的问题。
  • 但为什么在 Eclipse 中这是一个空值?
【解决方案4】:

您可以使用BufferedReader 获取用户输入。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;  

System.out.println("Enter your Account number: ");
accStr = br.readLine();

它将在accStr 中存储String 值,因此您必须使用Integer.parseInt 将其解析为int

int accInt = Integer.parseInt(accStr);

【讨论】:

    【解决方案5】:

    以下是获取键盘输入的方法:

    Scanner scanner = new Scanner (System.in);
    System.out.print("Enter your name");  
    String name = scanner.next(); // Get what the user types.
    

    【讨论】:

      【解决方案6】:

      最好的两个选项是BufferedReaderScanner

      使用最广泛的方法是Scanner,我个人更喜欢它,因为它简单易实现,以及将文本解析为原始数据的强大实用性。

      使用扫描仪的优势

      • Scanner 类易于使用
      • 轻松输入数字(int、short、byte、float、long 和 double)
      • 不检查异常,这样更方便。程序员要文明,并指定或捕获异常。
      • 能够读取行、空格和正则表达式分隔的标记

      BufferedInputStream 的优点


      总的来说,每种输入法都有不同的用途。

      • 如果您输入大量数据BufferedReader 可能 对你更好

      • 如果您输入大量数字 Scanner 会自动解析 很方便

      对于更多基本用途,我推荐Scanner,因为它更易于使用且更易于编写程序。下面是一个如何创建Scanner 的快速示例。我将在下面提供一个全面的示例,说明如何使用Scanner

      Scanner scanner = new Scanner (System.in); // create scanner
      System.out.print("Enter your name");       // prompt user
      name = scanner.next();                     // get user input
      

      (有关BufferedReader 的更多信息,请参阅How to use a BufferedReaderReading lines of Chars


      java.util.Scanner

      import java.util.InputMismatchException; // import the exception catching class
      import java.util.Scanner; // import the scanner class
      
      public class RunScanner {
      
          // main method which will run your program
          public static void main(String args[]) {
      
              // create your new scanner
              // Note: since scanner is opened to "System.in" closing it will close "System.in". 
              // Do not close scanner until you no longer want to use it at all.
              Scanner scanner = new Scanner(System.in);
      
              // PROMPT THE USER
              // Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println"
              System.out.println("Please enter a number");
      
              // use "try" to catch invalid inputs
              try {
      
                  // get integer with "nextInt()"
                  int n = scanner.nextInt();
      
      
                  System.out.println("Please enter a decimal"); // PROMPT
                  // get decimal with "nextFloat()"
                  float f = scanner.nextFloat();
      
      
                  System.out.println("Please enter a word"); // PROMPT
                  // get single word with "next()"
                  String s = scanner.next();
      
                  // ---- Note: Scanner.nextInt() does not consume a nextLine character /n 
                  // ---- In order to read a new line we first need to clear the current nextLine by reading it:
                  scanner.nextLine(); 
                  // ----
                  System.out.println("Please enter a line"); // PROMPT
                  // get line with "nextLine()"
                  String l = scanner.nextLine();
      
      
                  // do something with the input
                  System.out.println("The number entered was: " + n);
                  System.out.println("The decimal entered was: " + f);
                  System.out.println("The word entered was: " + s);
                  System.out.println("The line entered was: " + l);
      
      
              }
              catch (InputMismatchException e) {
                  System.out.println("\tInvalid input entered. Please enter the specified input");
              }
      
              scanner.close(); // close the scanner so it doesn't leak
          }
      }
      

      注意:ConsoleDataInputStream 等其他类也是可行的替代方案。

      Console 具有一些强大的功能,例如读取密码的能力,但是并非在所有 IDE(例如 Eclipse)中都可用。发生这种情况的原因是因为 Eclipse 将您的应用程序作为后台进程而不是作为具有系统控制台的顶级进程运行。 Here is a link 是一个关于如何实现 Console 类的有用示例。

      DataInputStream 主要用于以与机器无关的方式从底层输入流中读取作为原始数据类型的输入。 DataInputStream 通常用于读取二进制数据。它还提供了读取某些数据类型的便捷方法。例如,它有一个读取 UTF 字符串的方法,其中可以包含任意数量的行。

      但是,它是一个更复杂的类并且难以实现,因此不建议初学者使用。 Here is a link 是一个有用的例子,如何实现DataInputStream

      【讨论】:

      • 我要继续在这里打电话给获胜者。大部分是非常好的答案,虽然我希望它更深入地了解我何时想要使用DataInputStream——那里的描述听起来与Scanner 的用例相同:将数据读入原语。此外,如果有人处于不知道如何获取用户输入的阶段,他们很可能也不明白为什么标准库的某些部分在某些 IDE 中不可用。对我来说当然是这样——为什么Console 不可用?
      • 感谢您的反馈,我已尝试更新以包含更多说明。见quora.com/…stackoverflow.com/questions/27601520/…
      • 完美。现在这正是这个问题一直需要的答案。要是有办法让我登上顶峰就好了。
      • 好吧,任何愿意向下滚动的人都会得到一个很好的答案,然后它会慢慢上升:)
      • 谢谢。详细的信息答案。添加try-with-resource 会更好。
      【解决方案7】:

      您可以编写一个简单的程序来询问用户的姓名并打印回复使用的输入内容。

      或者要求用户输入两个数字,您可以对这些数字进行加、乘、减或除,然后打印用户输入的答案,就像计算器的行为一样。

      所以你需要 Scanner 类。你必须import java.util.Scanner; 并且在你需要使用的代码中

      Scanner input = new Scanner(System.in);
      

      输入是一个变量名。

      Scanner input = new Scanner(System.in);
      
      System.out.println("Please enter your name : ");
      s = input.next(); // getting a String value
      
      System.out.println("Please enter your age : ");
      i = input.nextInt(); // getting an integer
      
      System.out.println("Please enter your salary : ");
      d = input.nextDouble(); // getting a double
      

      看看这有何不同:input.next();i = input.nextInt();d = input.nextDouble();

      根据字符串,int 和 double 的变化方式相同。不要忘记代码顶部的 import 语句。

      另见博文"Scanner class and getting User Inputs"

      【讨论】:

        【解决方案8】:

        要读取一行或一个字符串,您可以使用BufferedReader 对象与InputStreamReader 对象组合,如下所示:

        BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
        String inputLine = bufferReader.readLine();
        

        【讨论】:

          【解决方案9】:

          在这里,程序要求用户输入一个数字。之后,程序打印数字的位数和位数的总和。

          import java.util.Scanner;
          
          public class PrintNumber {
              public static void main(String[] args) {
                  Scanner scan = new Scanner(System.in);
                  int num = 0;
                  int sum = 0;
          
                  System.out.println(
                      "Please enter a number to show its digits");
                  num = scan.nextInt();
          
                  System.out.println(
                      "Here are the digits and the sum of the digits");
                  while (num > 0) {
                      System.out.println("==>" + num % 10);
                      sum += num % 10;
                      num = num / 10;   
                  }
                  System.out.println("Sum is " + sum);            
              }
          }
          

          【讨论】:

            【解决方案10】:

            这是使用java.util.Scanner的问题中的程序:

            import java.util.Scanner;
            
            public class Example {
                public static void main(String[] args) {
                    int input = 0;
                    System.out.println("The super insano calculator");
                    System.out.println("enter the corrosponding number:");
                    Scanner reader3 = new Scanner(System.in);
                    System.out.println(
                        "1. Add | 2. Subtract | 3. Divide | 4. Multiply");
            
                    input = reader3.nextInt();
            
                    int a = 0, b = 0;
            
                    Scanner reader = new Scanner(System.in);
                    System.out.println("Enter the first number");
                    // get user input for a
                    a = reader.nextInt();
            
                    Scanner reader1 = new Scanner(System.in);
                    System.out.println("Enter the scend number");
                    // get user input for b
                    b = reader1.nextInt();
            
                    switch (input){
                        case 1:  System.out.println(a + " + " + b + " = " + add(a, b));
                                 break;
                        case 2:  System.out.println(a + " - " + b + " = " + subtract(a, b));
                                 break;
                        case 3:  System.out.println(a + " / " + b + " = " + divide(a, b));
                                 break;
                        case 4:  System.out.println(a + " * " + b + " = " + multiply(a, b));
                                 break;
                        default: System.out.println("your input is invalid!");
                                 break;
                    }
                }
            
                static int      add(int lhs, int rhs) { return lhs + rhs; }
                static int subtract(int lhs, int rhs) { return lhs - rhs; }
                static int   divide(int lhs, int rhs) { return lhs / rhs; }
                static int multiply(int lhs, int rhs) { return lhs * rhs; }
            }
            

            【讨论】:

            • 没有必要创建这么多Scanner对象;一个就足够了。
            【解决方案11】:
            Scanner input = new Scanner(System.in);
            String inputval = input.next();
            

            【讨论】:

              【解决方案12】:
              扫描仪输入=新扫描仪(System.in); int 整数=input.nextInt(); 字符串 string=input.next(); long longInteger=input.nextLong();

              【讨论】:

                【解决方案13】:

                只有一个额外的细节。如果您不想冒内存/资源泄漏的风险,则应在完成后关闭扫描器流:

                myScanner.close();
                

                请注意,java 1.7 及更高版本将此视为编译警告(不要问我是如何知道的 :-)

                【讨论】:

                • 但如果 Scanner 对 System.in 开放,则不是。您将无法在程序中再次将 Scanner 重新打开到 System.in。
                【解决方案14】:
                import java.util.Scanner; 
                
                class Daytwo{
                    public static void main(String[] args){
                        System.out.println("HelloWorld");
                
                        Scanner reader = new Scanner(System.in);
                        System.out.println("Enter the number ");
                
                        int n = reader.nextInt();
                        System.out.println("You entered " + n);
                
                    }
                }
                

                【讨论】:

                  【解决方案15】:

                  以下是已接受答案的更完善的版本,可解决两个常见需求:

                  • 重复收集用户输入,直到输入退出值
                  • 处理无效输入值(本例中为非整数)

                  代码

                  package inputTest;
                  
                  import java.util.Scanner;
                  import java.util.InputMismatchException;
                  
                  public class InputTest {
                      public static void main(String args[]) {
                          Scanner reader = new Scanner(System.in);
                          System.out.println("Please enter integers. Type 0 to exit.");
                  
                          boolean done = false;
                          while (!done) {
                              System.out.print("Enter an integer: ");
                              try {
                                  int n = reader.nextInt();
                                  if (n == 0) {
                                      done = true;
                                  }
                                  else {
                                      // do something with the input
                                      System.out.println("\tThe number entered was: " + n);
                                  }
                              }
                              catch (InputMismatchException e) {
                                  System.out.println("\tInvalid input type (must be an integer)");
                                  reader.nextLine();  // Clear invalid input from scanner buffer.
                              }
                          }
                          System.out.println("Exiting...");
                          reader.close();
                      }
                  }
                  

                  示例

                  Please enter integers. Type 0 to exit.
                  Enter an integer: 12
                      The number entered was: 12
                  Enter an integer: -56
                      The number entered was: -56
                  Enter an integer: 4.2
                      Invalid input type (must be an integer)
                  Enter an integer: but i hate integers
                      Invalid input type (must be an integer)
                  Enter an integer: 3
                      The number entered was: 3
                  Enter an integer: 0
                  Exiting...
                  

                  请注意,如果没有nextLine(),错误的输入将在无限循环中重复触发相同的异常。您可能希望根据具体情况改用next(),但要知道像this has spaces 这样的输入会产生多个异常。

                  【讨论】:

                    【解决方案16】:

                    main()旁边添加throws IOException,然后

                    DataInputStream input = new DataInputStream(System.in);
                    System.out.print("Enter your name");
                    String name = input.readLine();
                    

                    【讨论】:

                      【解决方案17】:

                      在java中获取输入很简单,你要做的就是:

                      import java.util.Scanner;
                      
                      class GetInputFromUser
                      {
                          public static void main(String args[])
                          {
                              int a;
                              float b;
                              String s;
                      
                              Scanner in = new Scanner(System.in);
                      
                              System.out.println("Enter a string");
                              s = in.nextLine();
                              System.out.println("You entered string " + s);
                      
                              System.out.println("Enter an integer");
                              a = in.nextInt();
                              System.out.println("You entered integer " + a);
                      
                              System.out.println("Enter a float");
                              b = in.nextFloat();
                              System.out.println("You entered float " + b);
                          }
                      }
                      

                      【讨论】:

                      • 是一样的。您始终可以使用数据类型 varName[] OR datatype[] varName 初始化一个数组
                      【解决方案18】:
                      import java.util.Scanner;
                      
                      public class Myapplication{
                           public static void main(String[] args){
                               Scanner in = new Scanner(System.in);
                               int a;
                               System.out.println("enter:");
                               a = in.nextInt();
                               System.out.println("Number is= " + a);
                           }
                      }
                      

                      【讨论】:

                        【解决方案19】:

                        您可以使用 BufferedReader 获得这样的用户输入:

                            InputStreamReader inp = new InputStreamReader(System.in);
                            BufferedReader br = new BufferedReader(inp);
                            // you will need to import these things.
                        

                        这就是你应用它们的方式

                            String name = br.readline(); 
                        

                        因此,当用户在控制台中输入他的名字时,“字符串名称”将存储该信息。

                        如果是要存储的数字,代码如下:

                            int x = Integer.parseInt(br.readLine());
                        

                        希望这有帮助!

                        【讨论】:

                          【解决方案20】:

                          可以是这样的……

                          public static void main(String[] args) {
                              Scanner reader = new Scanner(System.in);
                          
                              System.out.println("Enter a number: ");
                              int i = reader.nextInt();
                              for (int j = 0; j < i; j++)
                                  System.out.println("I love java");
                          }
                          

                          【讨论】:

                            【解决方案21】:

                            这是一个使用System.in.read() 函数的简单代码。这段代码只是写出输入的任何内容。如果您只想输入一次,则可以摆脱 while 循环,如果您愿意,可以将答案存储在字符数组中。

                            package main;
                            
                            import java.io.IOException;
                            
                            public class Root 
                            {   
                                public static void main(String[] args)
                                {
                                    new Root();
                                }
                            
                                public Root()
                                {
                                    while(true)
                                    {
                                        try
                                        {
                                            for(int y = 0; y < System.in.available(); ++y)
                                            { 
                                                System.out.print((char)System.in.read()); 
                                            }
                                        }
                                        catch(IOException ex)
                                        {
                                            ex.printStackTrace(System.out);
                                            break;
                                        }
                                    }
                                }   
                            }    
                            

                            【讨论】:

                              【解决方案22】:

                              我喜欢以下内容:

                              public String readLine(String tPromptString) {
                                  byte[] tBuffer = new byte[256];
                                  int tPos = 0;
                                  System.out.print(tPromptString);
                              
                                  while(true) {
                                      byte tNextByte = readByte();
                                      if(tNextByte == 10) {
                                          return new String(tBuffer, 0, tPos);
                                      }
                              
                                      if(tNextByte != 13) {
                                          tBuffer[tPos] = tNextByte;
                                          ++tPos;
                                      }
                                  }
                              }
                              

                              例如,我会这样做:

                              String name = this.readLine("What is your name?")
                              

                              【讨论】:

                                【解决方案23】:
                                import java.util.Scanner;
                                
                                public class Main {
                                    public static void main(String[] args) {
                                        System.out.println("Welcome to the best program in the world! ");
                                        while (true) {
                                            System.out.print("Enter a query: ");
                                            Scanner scan = new Scanner(System.in);
                                            String s = scan.nextLine();
                                            if (s.equals("q")) {
                                                System.out.println("The program is ending now ....");
                                                break;
                                            } else  {
                                                System.out.println("The program is running...");
                                            }
                                        }
                                    }
                                }
                                

                                【讨论】:

                                  【解决方案24】:
                                  import java.util.Scanner;
                                  
                                  public class userinput {
                                      public static void main(String[] args) {        
                                          Scanner input = new Scanner(System.in);
                                  
                                          System.out.print("Name : ");
                                          String name = input.next();
                                          System.out.print("Last Name : ");
                                          String lname = input.next();
                                          System.out.print("Age : ");
                                          byte age = input.nextByte();
                                  
                                          System.out.println(" " );
                                          System.out.println(" " );
                                  
                                          System.out.println("Firt Name: " + name);
                                          System.out.println("Last Name: " + lname);
                                          System.out.println("      Age: " + age);
                                      }
                                  }
                                  

                                  【讨论】:

                                    【解决方案25】:
                                    class ex1 {    
                                        public static void main(String args[]){
                                            int a, b, c;
                                            a = Integer.parseInt(args[0]);
                                            b = Integer.parseInt(args[1]);
                                            c = a + b;
                                            System.out.println("c = " + c);
                                        }
                                    }
                                    // Output  
                                    javac ex1.java
                                    java ex1 10 20 
                                    c = 30
                                    

                                    【讨论】:

                                    • 在不先检查数组长度的情况下访问args 的元素的制裁:downvote。
                                    【解决方案26】:

                                    正如其他人发布的那样,可以使用扫描仪进行键盘输入。但在这个高度图形化的时代,制作没有图形用户界面 (GUI) 的计算器毫无意义。

                                    在现代 Java 中,这意味着使用像 Scene Builder 这样的 JavaFX 拖放工具来布置类似于计算器控制台的 GUI。 请注意,使用 Scene Builder 非常简单,并且不需要额外的 Java 技能来处理您可能已经拥有的事件处理程序。

                                    对于用户输入,您应该在 GUI 控制台的顶部有一个宽的 TextField。

                                    这是用户输入他们想要执行功能的数字的地方。 在 TextField 下方,您将有一组功能按钮执行基本(即加/减/乘/除和内存/调用/清除)功能。 布置好 GUI 后,您可以添加将每个按钮功能链接到其 Java 实现的“控制器”引用,例如对项目控制器类中的方法的调用。

                                    This video 有点老了,但仍然显示了 Scene Builder 的易用性。

                                    【讨论】:

                                    • 这个答案被否决了 - 没有给出任何理由。对我来说,这是让用户输入 Java 应用程序的唯一可用方式。
                                    • 这非常有用,我不明白为什么它被否决了。但是,当前的答案和悬赏声明暗示他们正在为希望通过控制台获得输入的未来用户寻找答案。
                                    • 我只是没有看到任何 Java 用户——除非那些坚持使用旧版本 Java 编写的代码——对扫描仪键盘输入有任何用途。上次我在回答一个与赏金相关的帖子。 . .
                                    • 我完全理解您的投诉。我个人认为您的回答非常有用,所以我不明白为什么它被否决了。但是,我曾多次编写没有 GUI 的程序,因此我相信 Scanner 的正确代码非常适合。
                                    • 如果 OP 说这是一些低开销(嵌入式?)进程,屏幕 I/O 最少或没有,那很公平 - 他们需要扫描仪。但他们说没有这样的事情。 OP 本质上要求我们要么接受这个短语,“用户输入”,主要建议 keyboard 输入,要么邀请我们自己解释这个短语。 . .
                                    【解决方案27】:

                                    您可以使用Scanner 获取用户输入。您可以使用正确的方法对不同的数据类型使用正确的输入验证,例如next() 用于StringnextInt() 用于Integer

                                    import java.util.Scanner;
                                    
                                    Scanner scanner = new Scanner(System.in);
                                    
                                    //reads the input until it reaches the space
                                    System.out.println("Enter a string: ");
                                    String str = scanner.next();
                                    System.out.println("str = " + str);
                                    
                                    //reads until the end of line
                                    String aLine = scanner.nextLine();
                                    
                                    //reads the integer
                                    System.out.println("Enter an integer num: ");
                                    int num = scanner.nextInt();
                                    System.out.println("num = " + num);
                                    
                                    //reads the double value
                                    System.out.println("Enter a double: ");
                                    double aDouble = scanner.nextDouble();
                                    System.out.println("double = " + aDouble);
                                    
                                    
                                    //reads the float value, long value, boolean value, byte and short
                                    double aFloat = scanner.nextFloat();
                                    long aLong = scanner.nextLong();
                                    boolean aBoolean = scanner.nextBoolean();
                                    byte aByte = scanner.nextByte();
                                    short aShort = scanner.nextShort();
                                    
                                    scanner.close();
                                    

                                    【讨论】:

                                      【解决方案28】:

                                      获取用户输入的最简单方法是使用扫描仪。这是一个应该如何使用它的示例:

                                      import java.util.Scanner;
                                      public class main {
                                      public static void main(String[]args) {
                                      Scanner sc=new Scanner(System.in);
                                      int a;
                                      String b;
                                      System.out.println("Type an integer here: ");
                                      a=sc.nextInt();
                                      System.out.println("Type anything here:");
                                      b=sc.nextLine();
                                      

                                      代码行import java.util.Scanner; 告诉程序程序员将在他们的代码中使用用户输入。就像它说的那样,它导入了扫描仪实用程序。 Scanner sc=new Scanner(System.in); 告诉程序启动用户输入。完成此操作后,您必须创建一个没有值的字符串或整数,然后将它们放在a=sc.nextInt();a=sc.nextLine(); 行中。这为变量提供了用户输入的值。然后你可以在你的代码中使用它。希望这会有所帮助。

                                      【讨论】:

                                        【解决方案29】:

                                        使用 JOptionPane 即可实现。

                                        Int a =JOptionPane.showInputDialog(null,"Enter number:");
                                        

                                        【讨论】:

                                          猜你喜欢
                                          • 2011-02-07
                                          • 2018-08-09
                                          • 1970-01-01
                                          • 2010-11-10
                                          • 1970-01-01
                                          • 1970-01-01
                                          相关资源
                                          最近更新 更多