java - 为什么我用 while( in.hasNext() ) 从键盘获取值

标签 java while-loop

我是一个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/

相关文章:

java - 如何在 fragment 中放置或替换列表

java - 当我使用 jQuery EasyUI 时,如何在跨度中写入数据

java - 要修改的命令行输入和 XML

c# - while 循环没有正确检查所有条件?

python - while 语句和表达式

c - 为什么我不退出这个 while 循环?

java - Docker 容器运行一台计算机而不是另一台计算机

java - java中的循环if和else语句

javascript - 如何重复 123 1231 直到长度目标

c++多个条件以匹配确切的字符串