Johny
Johny

Reputation: 55

How to determine the largest digit in 5 digit integer?

How can I locate where among the 5 digit integer is the largest? it always print Rightmost even if the largest number is not the last digit.

Scanner in = new Scanner(System.in);

int num = in.nextInt();
int digit = 0, lastdigit = 0, middledigit = 0, firstdigit = 0; 

while(num > 0) {

 digit = num % 10;

 if(digit > lastdigit) {
  lastdigit = digit;
  System.out.println("Rightmost");
  return;
 }
 if(digit > middledigit) {
  middledigit = digit;
  System.out.println("Middle");
  return;
 }
 if(digit > firstdigit) {
  firstdigit = digit;
  System.out.println("Leftmost");
  return;
 } else {
    System.out.println("Unknown");
   }

num /= 10;

}

Input: 14632

Output: Rightmost

Expected output: Middle

and if none of the above is corret it will print Unknown.

Input: 77787

Output: Unknown

Upvotes: 0

Views: 1429

Answers (2)

user20191130
user20191130

Reputation: 360

You can create an array with the 5 digits, obtain the maximum, and then:

Arrays.asList(array).indexOf(maximum)

You can also use:

   int[] my_array={1,4,6,3,2};
   int index_of_largest=0;
   int maximum=array[0];    
   for(int i=1;i<array.length;i++){
        if(my_array[i]>maximum){
            index_of_largest =i;
            maximum=array[i];
        }
   }

Upvotes: 1

PIG208
PIG208

Reputation: 2380

The code doesn't work as intended because lastdigit is 0, and the program will return terminating the while loop as soon as it goes to the line return; in if(digit > lastdigit), in case the digit you check is greater than 0. This prevents your while loop from proceedings to the other digits to find the correct answer.

Also, the current if-statements in your while loop can't determine which digit it's checking right now. You might want to use a for loop instead or define a counter variable before your while loop.

Upvotes: 0

Related Questions