我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
我试图创建一个计算器,但我不能让它工作,因为我不知道如何获得用户输入。
如何在Java中获得用户输入?
当前回答
使用JOptionPane就可以实现。
Int a =JOptionPane.showInputDialog(null,"Enter number:");
其他回答
要读取一行或字符串,你可以使用BufferedReader对象和InputStreamReader对象结合使用,如下所示:
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
String inputLine = bufferReader.readLine();
在这里,程序要求用户输入一个数字。在此之后,程序打印数字的数字和数字的和。
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);
}
}
键盘输入使用扫描器是可能的,因为其他人已经张贴。但是在这个高度图形化的时代,没有图形用户界面(GUI)的计算器是毫无意义的。
在现代Java中,这意味着使用JavaFX拖放工具(如Scene Builder)来布局类似计算器控制台的GUI。 请注意,使用Scene Builder直观上很简单,不需要额外的Java技能来处理它的事件处理程序。
对于用户输入,在GUI控制台的顶部应该有一个宽的TextField。
这是用户输入他们想要执行功能的数字的地方。 在TextField下面,你会有一个函数按钮数组做基本的(即加/减/乘/除和记忆/召回/清除)功能。 一旦GUI布局好了,你就可以添加“控制器”引用,将每个按钮功能链接到它的Java实现,例如在项目的控制器类中调用方法。
这个视频有点老,但仍然显示了场景生成器是多么容易使用。
最简单的方法之一是使用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();
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