我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
当前回答
获取用户输入的最简单方法是使用Scanner。下面是一个如何使用它的例子:
import java.util.Scanner;
public class main {
public static void main(String[]args) {
Scanner sc=new Scanner(System.in);
int a;
String b;
System.out.println("Type an integer here: ");
a=sc.nextInt();
System.out.println("Type anything here:");
b=sc.nextLine();
代码行导入java.util.Scanner;告诉程序程序员将在他们的代码中使用用户输入。如它所说,它导入了扫描仪实用程序。Scanner sc=new Scanner(System.in);告诉程序启动用户输入。在你这样做之后,你必须创建一个没有值的字符串或整数,然后把它们放在一行a=sc.nextInt();或= sc.nextLine();。这为变量提供了用户输入的值。然后可以在代码中使用它。希望这能有所帮助。
其他回答
在这里,程序要求用户输入一个数字。在此之后,程序打印数字的数字和数字的和。
import java.util.Scanner;
public class PrintNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = 0;
int sum = 0;
System.out.println(
"Please enter a number to show its digits");
num = scan.nextInt();
System.out.println(
"Here are the digits and the sum of the digits");
while (num > 0) {
System.out.println("==>" + num % 10);
sum += num % 10;
num = num / 10;
}
System.out.println("Sum is " + sum);
}
}
你可以像这样使用BufferedReader获取用户输入:
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
// you will need to import these things.
这就是应用它们的方法
String name = br.readline();
因此,当用户在控制台中输入他的名字时,“字符串名称”将存储该信息。
如果它是一个你想要存储的数字,代码将像这样:
int x = Integer.parseInt(br.readLine());
希望这能有所帮助!
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);
}
}
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类或Console类
Console console = System.console();
String input = console.readLine("Enter input:");