Home > Mobile >  Checking an array for descending or increasing order inside scanner loop
Checking an array for descending or increasing order inside scanner loop

Time:06-22

I need to write a program that checks if the boys (3) are arranged in ascending or descending order by height. I can use 3 times scanner.nextInt():

int a = scanner.nextInt();

than use if statement :

if (a >= b && b >= c || c >= b && b >= a) {
    System.out.println("true");
} else {
    System.out.println("false");
}

and it's work perfectly. I also can create an array and check it, but it's not interesting. But I want to try solve it using 'for' loop for scanning input values within loop and check conditions:

final int numberOfBoys = 3;
boolean result = false;
    
for (int i = 0; i < numberOfBoys; i  ) {
    int boyHeight = scanner.nextInt();
    int a = boyHeight;
    if (a >= boyHeight || a <= boyHeight) {
        result = true;
    }
}
    
System.out.println(result);

Here I assigned input value of 'boyHeight' to 'a' variable and compare it with next scanning value, but I always get "true" result which is wrong.

CodePudding user response:

Here is a way to determine if all three are in descending order, ascending order, or not in order at all.

 1.   Scanner scanner = new Scanner(System.in);
 2.   int[] heights = new int[3];
 3.   heights[0] = scanner.nextInt();
 4.   heights[1] = scanner.nextInt();
 5.   heights[2] = scanner.nextInt();
 6.   
 7.   if (heights[0] >= heights[1] && heights[1] >= heights[2]) {
 8.      System.out.println("descending order");
 9.   } else if (heights[0] <= heights[1] && heights[1] <= heights[2]) {
10.      System.out.println("ascending order");
11.   } else {
12.      System.out.println("not in order");
13.   }

A few notes:

  • line 2: this is hard-coded to 3, obviously it wouldn't work if you want to compare with 4 or some other number
  • lines 3-5: also hard-coded to 3, but easily could be moved into a loop
  • line 7: if item 0 is larger than 1, and 1 is larger than 2, that's clearly "descending". This could be reworked to fit with a loop, but it's perhaps clearer to see this way.
  • line 9: similar to 7, just compare the other direction
  • line 12: this is the case for mixed ordering, neither ascending nor descending

If you want to use a loop, here's an edit to replace lines 2-5:

int totalToCheck = 3;
int[] heights = new int[totalToCheck];
for (int i = 0; i < totalToCheck; i  ) {
    heights[i] = scanner.nextInt();
}
  • Related