在这个程序中,你将学会用Java打印一个由用户输入的数字。该整数使用System.in存储在一个变量中,并使用System.out显示在屏幕上。
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
类的对象,即阅读器,以接受来自标准输入的输入,即keyboard
。
然后,Enter a number
提示被打印出来,给用户一个视觉提示,告诉他们接下来应该做什么。
reader.nextInt()
然后从键盘上读取所有输入的整数,除非它遇到一个新行字符\n (Enter)
。然后,输入的整数被保存到整数变量编号中。
如果你输入任何不是整数的字符,编译器将抛出一个InputMismatchException
。
最后,数字被打印到标准输出(System.out
)--使用函数println()
的计算机屏幕。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.programiz.com/java-programming/examples/print-integer
内容来源于网络,如有侵权,请联系作者删除!