pol*_*nts 139
你可以使用java.util.Scanner(API):
import java.util.Scanner;
//...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
Run Code Online (Sandbox Code Playgroud)
它还可以使用正则表达式等对输入进行标记.API有示例,此站点中还有许多其他示例(例如,如果输入错误的类型,如何防止扫描程序抛出异常?).
mis*_*tor 31
如果您使用的是Java 6,则可以使用以下oneliner从控制台读取整数:
int n = Integer.parseInt(System.console().readLine());
Run Code Online (Sandbox Code Playgroud)
Sri*_*ddy 17
这里我提供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);
}
}
Run Code Online (Sandbox Code Playgroud)
例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);
}
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢第一个例子,它很容易理解.
您可以在此网站上在线编译和运行JAVA程序:http://ideone.com
the*_*ost 11
检查一下:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
上面的第二个答案是最简单的一个。
int n = Integer.parseInt(System.console().readLine());
Run Code Online (Sandbox Code Playgroud)
问题是“如何从标准输入读取”。
控制台是一种通常与键盘和显示器相关联的设备,从中启动程序。
您可能希望测试是否没有可用的 Java 控制台设备,例如 Java VM 不是从命令行启动或标准输入和输出流被重定向。
Console cons;
if ((cons = System.console()) == null) {
System.err.println("Unable to obtain console");
...
}
Run Code Online (Sandbox Code Playgroud)
使用控制台是一种输入数字的简单方法。结合 parseInt()/Double() 等。
s = cons.readLine("Enter a int: ");
int i = Integer.parseInt(s);
s = cons.readLine("Enter a double: ");
double d = Double.parseDouble(s);
Run Code Online (Sandbox Code Playgroud)
小智 5
检查这个:
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());
}
}
Run Code Online (Sandbox Code Playgroud)