要从控制台读取整数,请使用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