从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 红包祝福语简短10字
18 周六早晨祝福语简短