【问题标题】:How to read integer value from the standard input in Java如何从 Java 中的标准输入中读取整数值
【发布时间】:2011-01-31 03:43:21
【问题描述】:

我可以使用什么类来读取 Java 中的整数变量?

【问题讨论】:

    标签: java io


    【解决方案1】:

    检查这个:

    public static void main(String[] args) {
        String input = null;
        int number = 0;
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            input = bufferedReader.readLine();
            number = Integer.parseInt(input);
        } catch (NumberFormatException ex) {
           System.out.println("Not a number !");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

    • 捕获NumberFormatException 然后打印堆栈跟踪有什么意义?
    【解决方案2】:

    您可以使用java.util.Scanner (API):

    import java.util.Scanner;
    
    //...
    
    Scanner in = new Scanner(System.in);
    int num = in.nextInt();
    

    它还可以使用正则表达式等对输入进行标记。API 有示例,并且此站点中还有许多其他示例(例如How do I keep a scanner from throwing exceptions when the wrong type is entered?)。

    【讨论】:

    • 我试图在我的 Eclipse ID 中运行它,没有语法错误,但是当我尝试输出读取的整数值时,它在控制台输出中没有显示任何内容。为什么会这样?
    • @polygenelubricants: in.nextInt() 只接受 int 值而不是 Integer 值
    【解决方案3】:

    如果您使用的是 Java 6,则可以使用以下 oneliner 从控制台读取整数:

    int n = Integer.parseInt(System.console().readLine());
    

    【讨论】:

    • 我想评论一下,在大多数 IDE 下,当通过启动器调用应用程序时 System.console 将返回 null,这使得调试变得困难。对于 IDEA、Eclipse 和 NetBeans 来说,这似乎是正确的。
    • 如果他输入一个字符串或“Enter”,它会抛出一个 NumberFormatException。所以最好在解析成Integer之前控制字符串
    • 如果该行中有多个整数,用空格分隔怎么办?
    • @LostMohican,有办法使用扫描仪读取空格分隔的标记。
    • 这在空白处窒息。
    【解决方案4】:

    这里我提供 2 个示例来从标准输入中读取整数值

    示例 1

    import java.util.Scanner;
    public class Maxof2
    { 
      public static void main(String args[])
      {
           //taking value as command line argument.
            Scanner in = new Scanner(System.in); 
           System.out.printf("Enter i Value:  ");
           int i = in.nextInt();
           System.out.printf("Enter j Value:  ");
           int j = in.nextInt();
           if(i > j)
               System.out.println(i+"i is greater than "+j);
           else
               System.out.println(j+" is greater than "+i);
       }
     }
    

    示例 2

    public class ReadandWritewhateveryoutype
    { 
      public static void main(String args[]) throws java.lang.Exception
      {
    System.out.printf("This Program is used to Read and Write what ever you type \nType  quit  to Exit at any Moment\n\n");
        java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
         String hi;
         while (!(hi=r.readLine()).startsWith("quit"))System.out.printf("\nYou have typed: %s \n",hi);
         }
     }
    

    我更喜欢第一个示例,它简单易懂。
    您可以在这个网站上在线编译和运行JAVA程序:http://ideone.com

    【讨论】:

    • ex 2 可能不是引入输入流的最佳方式......或者我猜“系统的输入对象”对于 OOD、Java 或编码的新手来说——所有这些都是描述性的代码,您将关键对象命名为“r” .... 一个聪明人,嗯? xD +1
    • 示例 1 不受虚假格式输入的保护
    【解决方案5】:

    上面的第二个答案是最简单的。

    int n = Integer.parseInt(System.console().readLine());
    

    问题是“如何从标准输入中读取”。

    控制台是一种通常与启动程序的键盘和显示器相关联的设备。

    您可能希望测试是否没有可用的 Java 控制台设备,例如Java VM 未从命令行启动或标准输入和输出流被重定向。

    Console cons;
    if ((cons = System.console()) == null) {
        System.err.println("Unable to obtain console");
        ...
    }
    

    使用控制台是一种输入数字的简单方法。结合 parseInt()/Double() 等。

    s = cons.readLine("Enter a int: ");
    int i = Integer.parseInt(s);    
    
    s = cons.readLine("Enter a double: ");
    double d = Double.parseDouble(s);
    

    【讨论】:

    • -1 不回答问题。他不想从控制台读取,而是从标准输入读取。
    • 问题明确指出他不想从控制台读取。无论如何,感谢您提供有关如何从控制台读取的一些信息。
    【解决方案6】:

    检查这个:

    import java.io.*;
    public class UserInputInteger
    {
            public static void main(String args[])throws IOException
            {
            InputStreamReader read = new InputStreamReader(System.in);
            BufferedReader in = new BufferedReader(read);
            int number;
                    System.out.println("Enter the number");
                    number = Integer.parseInt(in.readLine());
        }
    }
    

    【讨论】:

      【解决方案7】:

      这引起了头疼,因此我更新了一个解决方案,该解决方案将在 2014 年 12 月使用用户可用的最常见的硬件和软件工具运行。请注意,JDK/SDK/JRE/Netbeans 及其后续类、模板库编译器、编辑器和调试器是免费的。

      该程序已使用 Java v8 u25 进行了测试。它是使用
      编写和构建的 Netbeans IDE 8.0.2,JDK 1.8,操作系统是 win8.1(道歉),浏览器是 Chrome(双重道歉) - 旨在帮助 UNIX-cmd-line OG 处理现代 GUI-Web-based IDE 零成本 - 因为信息(和 IDE)应该始终是免费的。 通过 Tapper7。适合所有人。

      代码块:

          package modchk; //Netbeans requirement.
          import java.util.Scanner;
          //import java.io.*; is not needed Netbeans automatically includes it.           
          public class Modchk {
              public static void main(String[] args){
                  int input1;
                  int input2;
      
                  //Explicity define the purpose of the .exe to user:
                  System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n"
                  + "Commented and coded for C/C++ programmers new to Java\n");
      
                  //create an object that reads integers:
                  Scanner Cin = new Scanner(System.in); 
      
                  //the following will throw() if you don't do you what it tells you or if 
                  //int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9
                  System.out.println("Enter an integer wiseguy: ");
                  input1 = Cin.nextInt(); //this command emulates "cin >> input1;"
      
                  //I test like Ernie Banks played hardball: "Let's play two!"
                  System.out.println("Enter another integer...anyday now: ");
                  input2 = Cin.nextInt(); 
      
                  //debug the scanner and istream:
                  System.out.println("the 1st N entered by the user was " + input1);
                  System.out.println("the 2nd N entered by the user was " + input2);
      
                  //"do maths" on vars to make sure they are of use to me:
                  System.out.println("modchk for " + input1);
                  if(2 % input1 == 0){
                      System.out.print(input1 + " is even\n"); //<---same output effect as *.println
                      }else{
                      System.out.println(input1 + " is odd");
                  }//endif input1
      
                  //one mo' 'gain (as in istream dbg chk above)
                  System.out.println("modchk for " + input2);
                  if(2 % input2 == 0){
                      System.out.print(input2 + " is even\n");
                      }else{
                      System.out.println(input2 + " is odd");
                  }//endif input2
              }//end main
          }//end Modchk
      

      【讨论】:

        猜你喜欢
        • 2014-08-22
        • 2018-04-28
        • 2019-07-26
        • 2011-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多