示例:如何打印用户输入的整数
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Creates a reader instance which takes
// input from standard input - keyboard
Scanner reader = new Scanner(System.in);
System.out.print("Enter a number: ");
// nextInt() reads the next integer from the keyboard
int number = reader.nextInt();
// println() prints the following line to the output screen
System.out.println("You entered: " + number);
}
}
输出
Enter a number: 10 You entered: 10
在此程序中,创建了一个Scanner类的对象reader,用于从标准输入(即键盘
)获取输入。
然后,打印Enter a number
提示,为用户提供关于他们下一步应该做什么的视觉提示。
reader.nextInt()
会读取键盘上输入的所有整数,直到遇到换行符\n (Enter)
。然后,输入的整数被保存在整数变量number中。
如果您输入任何非整数字符,编译器将抛出InputMismatchException
。
最后,使用println()
函数将number打印到标准输出(System.out
)——计算机屏幕上。