Advertisement
mmayoub

Loops - execise no 03, slide no 64

Jun 27th, 2017
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.03 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class LoopsEx03Slide64 {
  6.  
  7.     public static void main(String[] args) {
  8.         // input: integer number. example: 512624
  9.         // output: maximum digit in the number. example: 6
  10.  
  11.         // create a scanner
  12.         Scanner s = new Scanner(System.in);
  13.  
  14.         // ask for input
  15.         System.out.print("Enter an integer number: ");
  16.         // get and save input value
  17.         int n = s.nextInt();
  18.  
  19.         // close scanner
  20.         s.close();
  21.  
  22.         int maxDigit = n % 10; // calculated: maximum digit so far
  23.         int tmp = n / 10; // calculated: number with digits to be checked
  24.  
  25.         // while there are more digits to check
  26.         while (tmp > 0) {
  27.             // calculate most right digit
  28.             int digit = tmp % 10; // calculated: current digit to be checked
  29.  
  30.             // if even digit then
  31.             if (digit > maxDigit) {
  32.                 // set it to be the maximum
  33.                 maxDigit = digit;
  34.             }
  35.             tmp /= 10; // drop this digit and continue to check the others
  36.         }
  37.  
  38.         // display output on the screen
  39.         System.out.printf("n=%d , maximum digit=%d\n", n, maxDigit);
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement