Integer Division Tester

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page
Enter first  integer:
12 -8
Enter second integer:
The sum of 12 plus -8 is 4

Answer:

The nextInt() method scans through the input stream character by character, grouping characters into groups that can be converted into numeric data. It ignores any spaces and end-of-lines that may separate these groups.

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 the input as separate "lines". But a Scanner sees a stream of characters. After it has scanned a group, it stops at where ever it is and waits until it is asked to scan again.

Integer Division Tester

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

  • The user enters two integers, dividend and divisor.
  • The program calculates and prints the quotient and the remainder.
  • The program calculates and prints quotient * divisor + remainder.
import java.util.Scanner;
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) );
  }
}

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

QUESTION 17:

Do these notes still have your undivided attention?