go to previous page   go to home page   go to next page hear noise highlighting
Enter first  integer:
12 -8
Enter second integer:
The sum of 12 plus -8 is 4

Answer:

During the first call to nextInt(), the Scanner found the characters "12" , converted them to an int and stopped. It did what the program requested.

During the second call to nextInt(), the Scanner continued scanning from where it stopped. It found the characters "-8" , and converted them to an int.

The action of the Scanner does not depend on the prompt the program wrote out.


Integer Division Tester

The nextInt() method scans through the input stream, character by character, building a group that can be converted into numeric data. It scans over spaces and end-of-lines that may separate one group from another. Once it has found a group, it stops scanning.

In the above, the user entered two groups on one line. Each call to nextInt() scanned in one group.

It is tempting to think of user input as a sequence of separate "lines". But a Scanner sees a stream of characters with occasional line-separator characters. After it has scanned a group, it stops at where ever it is and waits until it is asked to scan again.



Here is a new program made by modifying the previous program.

Run the program a few times. See what happens when negative integers are input.


import java.util.Scanner;
public class IntDivideTest
{
  public static void main (String[] args) 
  { 
    Scanner scan = new Scanner( System.in );
 
    int dividend, divisor ;                      // int versions of input
    int quotient, remainder ;                    // results of "/" and "%"

    System.out.println("Enter the dividend:");   // read the dividend
    dividend = scan.nextInt();          

    System.out.println("Enter the divisor:");    // read the divisor
    divisor  = scan.nextInt();          

    quotient = dividend / divisor ;              // perform int math
    remainder= dividend % divisor ;

    System.out.println( dividend + " / " + divisor + " is " + quotient );
    System.out.println( dividend + " % " + divisor + " is " + remainder );
    System.out.println( quotient + " * " + divisor + 
        " + " + remainder + " is " + (quotient*divisor+remainder) );
  }
}

QUESTION 17:

Do these notes still have your undivided attention?


go to previous page   go to home page   go to next page