【问题标题】:Getting Keyboard Input获取键盘输入
【发布时间】:2013-07-06 11:12:16
【问题描述】:

如何在 Java 的控制台中从用户那里获得简单的键盘输入(整数)?我使用 java.io.* 东西完成了这个,但它说它已被弃用。

我现在应该怎么做?

【问题讨论】:

  • 要具体。 'java.io.* stuff' 没有被弃用。只有DataInputStream.readLine()。还有BufferedReader.readLine(),还有你在这里得到的其他建议。

标签: java input console keyboard


【解决方案1】:

你可以使用Scanner

先导入:

import java.util.Scanner;

那你就这样用吧。

Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

旁注:如果您将nextInt()nextLine() 一起使用,您可能会遇到一些麻烦,因为nextInt() 不会读取输入的最后一个换行符,因此nextLine() 不会以期望的方式执行行为。在上一个问题Skipping nextLine using nextInt 中阅读有关如何解决它的更多信息。

【讨论】:

  • 它说找不到符号扫描仪
  • @user1342573 你必须导入java.util.Scanner
  • Java 中的“输入”键盘和“输出”屏幕?
  • @Doeser 它们是System类中定义的类成员变量(静态),
  • 你为什么用键盘而不是in?
【解决方案2】:

你可以像这样使用 Scanner 类:

  import java.util.Scanner;

public class Main{
    public static void main(String args[]){

    Scanner scan= new Scanner(System.in);

    //For string

    String text= scan.nextLine();

    System.out.println(text);

    //for int

    int num= scan.nextInt();

    System.out.println(num);
    }
}

【讨论】:

    【解决方案3】:

    如果您想验证用户输入,也可以使用BufferedReader 来实现,如下所示:

    import java.io.BufferedReader;
    import java.io.InputStreamReader; 
    class Areas {
        public static void main(String args[]){
            float PI = 3.1416f;
            int r=0;
            String rad; //We're going to read all user's text into a String and we try to convert it later
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
            System.out.println("Radius?");
            try{
                rad = br.readLine(); //We read from user's input
                r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
                System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
            }
            catch(Exception e){
                System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
                Areas a = new Areas(); //We call this class again, so user can try it again
               //You can also print exception in case you want to see it as follows:
               // e.printStackTrace();
            }
        }
    }
    

    因为 Scanner 类不允许你这样做,或者没有那么容易......

    为了验证你是否使用了“try-catch”调用。

    【讨论】:

    • 我不明白你为什么说“因为 Scanner 类不允许你这样做,或者没有那么容易......”?国际海事组织你可以吗?
    • 另外,如果您想再次调用该类(或继续执行),您应该在实例化后调用“a.main(null)”,或者只执行“Areas.main(null)”
    • @KillBill 感谢您的评论,我忘记了这个问题,过几天我会尝试用更好的解释来编辑它,当我写这个答案时,我正在开始我的高中学习,今天我在一家 IT 公司工作,我会尽我所能写这篇文章;那时我是一个完全的新手,我现在不能编辑它,因为我有一些工作要做,但我保证我会编辑并让你知道。
    • @KillBill 感谢关于Areas.main(null) 的那个方法,但是在这种情况下,如果你想重用代码,你应该把它放在一个方法中,我的答案中的代码是在 main 方法上编写的,因为我尝试创建一个minimal reproducible example,这样任何想出我答案的人都可以轻松地复制粘贴它,看看它在没有额外工作的情况下做了什么
    • @Frakcool 我想说的是您的代码不会继续执行。无论如何,不​​用担心伴侣..如你所愿
    【解决方案4】:

    你可以使用 Scanner 类

    键盘读取(标准输入)您可以使用Scannerjava.util包中的一个类。

    Scanner 包用于获取基本类型的输入,如int, double 等和strings。这是在 Java 程序中读取输入的最简单方法,尽管效率不高。

    1. 要创建Scanner类的object,我们通常通过 预定义对象System.in,代表标准输入 流(键盘)。

    例如,此代码允许用户从 System.in 中读取一个数字:

    Scanner sc = new Scanner(System.in);
         int i = sc.nextInt();
    

    Scanner 类中的一些公共方法。

    • hasNext() 如果此扫描器中包含另一个令牌,则返回 true 输入。
    • nextInt() 将输入的下一个标记扫描为 int。
    • nextFloat() 将输入的下一个标记扫描为浮点数。
    • nextLine() 将此扫描器前进到当前行并返回被跳过的输入。
    • nextDouble() 将输入的下一个标记扫描为双精度。
    • close() 关闭此扫描仪。

    更多详情Public methods in Scanner class.

    例子:-

    import java.util.Scanner;                      //importing class
    
    class ScannerTest {
      public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);       // Scanner object
    
        System.out.println("Enter your rollno");
        int rollno = sc.nextInt();
        System.out.println("Enter your name");
        String name = sc.next();
        System.out.println("Enter your fee");
        double fee = sc.nextDouble();
        System.out.println("Rollno:" + rollno + " name:" + name + " fee:" + fee);
        sc.close();                              // closing object
      }
    }
    

    【讨论】:

      【解决方案5】:

      您可以使用 Scanner 获取下一行并对输入的行执行任何您需要执行的操作。您还可以使用 JOptionPane 弹出一个对话框,询问输入。

      扫描仪示例:

      Scanner input = new Scanner(System.in);
      System.out.print("Enter something > ");
      String inputString = input.nextLine();
      System.out.print("You entered : ");
      System.out.println(inputString);
      

      JOptionPane 示例:

      String input = JOptionPane.showInputDialog(null,
           "Enter some text:");
      JOptionPane.showMessageDialog(null,"You entered "+ input);
      

      您将需要这些导入:

      import java.util.Scanner;
      import javax.swing.JOptionPane;
      

      上面的一个完整的Java类

      import java.util.Scanner;
      import javax.swing.JOptionPane;
      public class GetInputs{
          public static void main(String args[]){
              //Scanner example
              Scanner input = new Scanner(System.in);
              System.out.print("Enter something > ");
              String inputString = input.nextLine();
              System.out.print("You entered : ");
              System.out.println(inputString);
      
              //JOptionPane example
              String input = JOptionPane.showInputDialog(null,
              "Enter some text:");
              JOptionPane.showMessageDialog(null,"You entered "+ input);
          }
      }
      

      【讨论】:

        【解决方案6】:

        导入:import java.util.Scanner;

        定义你的变量:String name; int age;

        定义您的扫描仪:Scanner scan = new Scanner(System.in);

        如果你想输入:

        • 文字:name = scan.nextLine();
        • 整数:age = scan.nextInt();

        如果不再需要,请关闭扫描仪:scan.close();

        【讨论】:

          【解决方案7】:

          如果你有 Java 6(你应该有,顺便说一句)或更高版本,那么只需这样做:

           Console console = System.console();
           String str = console.readLine("Please enter the xxxx : ");
          

          请记得做:

           import java.io.Console;
          

          就是这样!

          【讨论】:

            【解决方案8】:
            import java.util.Scanner; //import the framework
            
            
            Scanner input = new Scanner(System.in); //opens a scanner, keyboard
            System.out.print("Enter a number: "); //prompt the user
            int myInt = input.nextInt(); //store the input from the user
            

            如果您有任何问题,请告诉我。相当不言自明。我评论了代码,以便您阅读。 :)

            【讨论】:

            • @nachokk 我实际上是在你发布的时候输入的。我的错。
            【解决方案9】:

            添加行:

            import java.util.Scanner;
            

            然后创建Scanner类的对象:

            Scanner s = new Scanner(System.in);
            

            现在您可以随时拨打电话:

            int a = Integer.parseInt(s.nextLine());
            

            这将从您的键盘存储integer 值。

            【讨论】:

            • 你可以打电话给nextInt()而不是nextLine()
            【解决方案10】:

            在java中我们可以通过6种方式读取输入值:

            1. 扫描仪类
            2. BufferedReader
            3. 控制台类
            4. 命令行
            5. AWT、字符串、GUI
            6. 系统属性
            1. Scanner 类: 存在于 java.util.* 中;包,它有很多方法,根据您的输入类型,您可以使用这些方法。一种。 nextInt() b. nextLong() C. nextFloat() d. nextDouble() e.下一个() f。下一条线();等等……
            import java.util.Scanner;
            public class MyClass {
                public static void main(String args[]) {
                    Scanner sc = new Scanner(System.in);
                    System.out.println("Enter a :");
                    int a = sc.nextInt();
                    System.out.println("Enter b :");
                    int b = sc.nextInt();
                    
                    int c = a + b;
                    System.out.println("Result: "+c);
                }
            }
            
            1. BufferedReader 类:存在于 java.io.* 中; package & 它有很多方法,从键盘读取值使用 "readLine()" :这种方法一次读取一行。
            import java.io.BufferedReader;
            import java.io.*;
            public class MyClass {
                public static void main(String args[]) throws IOException {
                   BufferedReader br = new BufferedReader(new BufferedReader(new InputStreamReader(System.in)));
                    System.out.println("Enter a :");
                    int a = Integer.parseInt(br.readLine());
                    System.out.println("Enter b :");
                    int b = Integer.parseInt(br.readLine());
                    
                    int c = a + b;
                    System.out.println("Result: "+c);
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-10-19
              • 2010-11-29
              • 1970-01-01
              • 2015-07-06
              • 1970-01-01
              • 2014-12-28
              相关资源
              最近更新 更多