IT-Swarm.Net

如何从Java中的标准输入读取整数值

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

105
Nehil Verma

你可以使用Java.util.Scanner_ api _ ):

import Java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

它还可以使用正则表达式等标记输入.API有示例,并且此站点中还有许多其他示例(例如 如何在输入错误类型时防止扫描程序抛出异常? )。

133
polygenelubricants

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

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

这里我提供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

17
Srivastav Reddy

检查一下:

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();
    }
}
11
thelost

检查一下:

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());
    }
}
4
madhav

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

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);
4
Najib Tounsi

这会引起麻烦,所以我更新了一个解决方案,该解决方案将使用2014年12月用户可用的最常用硬件和软件工具运行。请注意JDK/SDK/JRE/Netbeans及其后续类,模板库编译器,编辑器和调试器是自由。

该程序使用Java v8 u25进行了测试。它是使用编写和构建的
Netbeans IDE 8.0.2,JDK 1.8,操作系统是win8.1(道歉),浏览器是Chrome(双道歉) - 旨在帮助UNIX-cmd-line OG与现代交易ZERO COST的基于GUI的基于Web的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
3
Tapper7