Brainiac Khan
Brainiac Khan

Reputation: 103

Why am i geting the value from keyboard with while( in.hasNext() )

I am a java beginer, my confusion regarding the following program is, why it assigns the value, i enter from keyboard at while( in.hasNext() )to the total variable, and process the value of total = in.intNext() for the while condition ?

Confusion

  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++;
   }

My confusion is the condition checking of while loop, which normally checks a condition first, and then proceed to the statements, but in this program, when i enter an Integer Value at the while( in.hasNext() ), it not only makes the condition true, but also assign that value to the total variable, so my question,

Why does it assigns the value, instead of taking another value from me at total = in.nextInt() ?

Since i looked for hasNext() method, which only returns True if there is a value.

Complete Program

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

Upvotes: 0

Views: 201

Answers (1)

Alix Martin
Alix Martin

Reputation: 332

the value from the keyboard is not read on the while( in.hasNext() ) line, but in the count += in.nextInt(); statement

Upvotes: 1

Related Questions