[英]Why am i geting the value from keyboard with while( in.hasNext() )
我是一名Java初學者,我對以下程序感到困惑,為什么要分配值,我在while( in.hasNext() )
從鍵盤輸入total
變量,並處理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 loop
的條件檢查,通常先檢查條件,然后執行語句,但是在此程序中,當我在while( in.hasNext() )
輸入Integer Value時,它不僅使條件為真,但還要將該值分配給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();
聲明
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.