我是一个java初学者,我对以下程序的困惑是,为什么它分配值,我从键盘输入 while( in.hasNext() )
到 total
变量,并处理 while 条件的 total = in.intNext()
的值?
困惑
System.out.print("Enter an Integer value or ctrl+z to terminate: ");
while ( in.hasNext() ) // Check for New Vlaue
{
System.out.print("Enter an Integer value or ctrl+z to terminate: ");
total += in.nextInt(); // Take input for Count
count++;
}
我的困惑是while循环
的条件检查,它通常首先检查条件,然后继续执行语句,但在这个程序中,当我在处输入一个整数值时while( in.hasNext() )
,它不仅使条件成立,而且将该值分配给 total
变量,所以我的问题,
为什么它要分配值,而不是在 total = in.nextInt()
处从我那里获取另一个值?
因为我寻找 hasNext()
方法,如果有值,它只返回 True。
完整计划
import java.util.Scanner;
class Practice
{
public static void main( String[] args )
{
int count=0;
int total = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter an Integer value or ctrl+z to terminate: ");
while ( in.hasNext() ) // Check for New Vlaue
{
System.out.print("Enter an Integer value or ctrl+z to terminate: ");
total += in.nextInt(); // Take input for Count
count++;
}
System.out.printf("\nTatal values are: %d\nToatl of count is : %d",count,total);
} // end main
} // end class Practice
最佳答案
键盘上的值不是在 while( in.hasNext() )
行读取的,而是在 count += in.nextInt();
语句中读取的
关于java - 为什么我用 while( in.hasNext() ) 从键盘获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12706266/