从Java中的控制台读取整数
要从控制台读取整数,请使用Scanner类。
Scanner myInput = new Scanner( System.in );
允许用户使用方法添加一个整数nextInt()。
System.out.print( "Enter first integer: " ); int a = myInput.nextInt();
同样,在新变量中输入另一个输入。
System.out.print( "Enter second integer: " ); Int b = myInput.nextInt();
让我们看完整的例子。
示例
import java.util.Scanner;
public class Demo {
public static void main( String args[] ) {
Scanner myInput = new Scanner( System.in );
int a;
int b;
int sum;
System.out.print( "Enter first integer: " );
a = myInput.nextInt();
System.out.print( "Enter second integer: " );
b = myInput.nextInt();
sum = a + b;
System.out.printf( "Sum = %d\n", sum );
}
}我们从控制台添加了以下两个整数值。
5 10
添加值并运行程序后,可以看到以下输出。
Enter first integer: 5 Enter second integer: 10 Sum = 15
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短