Task: Create an array of 4 random numbers. To display them on the screen, and from the new line to display a message about what kind of sequence it is (increasing, decreasing or none).

Here is my code:

public class four { public static void main(String[] args) { int[] mas = new int[4]; for (int i = 0; i < mas.length; i++) { Random ran = new Random(); mas[i] = ran.nextInt(90) + 10; System.out.print(mas[i] + " "); } System.out.println(" "); if (mas[0] < mas[1] & mas[1] < mas[2] & mas[2] < mas[3]) { System.out.println("Последовательность строго возрастающая"); } else if (mas[0] > mas[1] & mas[1] > mas[2] & mas[2] > mas[3]) { System.out.println("Последовательность строго убывающая"); } else System.out.println("Другая последовательность"); } } 

I would like to know whether it is possible to do this task differently. For example, no longer from 4 numbers, but let's say 50 or 100.

  • one
    If you have an array of 50 random numbers, I doubt that there will be a decreasing or increasing sequence))) And you have a bitwise operation condition, kmk, not a logical one - Alexey Shimansky
  • Yes)) This is true, but still I wanted to know how to do the same task using a cycle. - Alex
  • There even cycles are not needed - Alexey Shimansky
  • Can I do something else through the cycle or not? - Alex
  • ....... You can))) - Alexey Shimansky

1 answer 1

Something like this. Further it is not difficult to pull the methods.

 int[] generateSequesce(int length, int maxValue, int minValue){ Random ran = new Random(); int[] result = new int[length]; for (int i = 0; i < length; i ++){ result[i] = ran.nextInt(maxValue-minValue) + minValue; } return result; } boolean isIncreasing(int[] sequence){ int lastValue = sequence[0]; for (int i = 1; i < sequence.length; i++){ if (lastValue < sequence[i]){ lastValue = sequence[i]; } else { return false; } } return true; } boolean isDecreasing(int[] sequence){ int lastValue = sequence[0]; for (int i = 1; i < sequence.length; i++){ if (lastValue > sequence[i]){ lastValue = sequence[i]; } else { return false; } } return true; } 
  • Thank. I will try) - Alex