我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
当前回答
然后,Add在main()旁边抛出IOException
DataInputStream input = new DataInputStream(System.in);
System.out.print("Enter your name");
String name = input.readLine();
其他回答
要读取一行或字符串,你可以使用BufferedReader对象和InputStreamReader对象结合使用,如下所示:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
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
你可以做一个简单的程序,要求用户的名字和打印任何回复使用输入。
或者让用户输入两个数字,你可以加、乘、减或除这些数字,并打印出用户输入的答案,就像计算器的行为一样。
你需要Scanner类。你必须导入java。util。scanner;在你需要使用的代码中
Scanner input = new Scanner(System.in);
Input是一个变量名。
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();
根据String类型,int和double类型以同样的方式变化。不要忘记代码顶部的import语句。
请参见博客文章“扫描器类和获取用户输入”。
最简单的方法之一是使用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();
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);
}
}