the array is filled with random numbers from -10 to 5. It is necessary to display the sum of the first and last positive. Java

int[] array = new int[30]; int x = 0; int counter = 0; for (int i = 0; i < array.length; i++) { array[i] = (int) (Math.random() * 16) - 10; if (array[i] > 0) { System.out.println(array[i]); } } 

At the moment, I was able to fill in random numbers and output positive all. But as it came to finding the first and the last, I was at a dead end. Please help in finding the first and last positive. Zero can be considered as positive.

  • is 0 a positive element? - Alexey Shimansky
  • find positive numbers, the first of them is memorized in one variable, the last of them is in the second - Vladyslav Matviienko
  • @ metalurgus Do I have to sort it out here? - Olexiy Yelizarenko
  • I recommend using the terms positive and non-negative in order to avoid discrepancies. - D-side

2 answers 2

This will work:

 // Инициализация переменных int[] array = new int[30]; int firstNum=-1; int lastNum=-1; int sum; //Заполнение массива for (int i = 0; i < array.length; i++) { array[i] = (int) (Math.random() * 16) - 10; } //Поиск первого и последнего положительного числа for (int i = 0; i < array.length; i++) { if(array[i]>=0){ // Если первое положительное число еще не найдено if (firstNum==-1){ firstNum=array[i]; } // Каждый раз обновляем переменную последнего положительного числа lastNum=array[i]; } } // Находим сумму sum=firstNum+lastNum; 
  • Thank you very much. I was able to solve the problem myself using array inversion. - Olexiy Yelizarenko

Thank you all for the feedback. Do not judge strictly. We learn.

Solved the problem in such a way. I used array inversion. It is interesting to know the opinion of experienced guys.

  int [] array = new int [30]; int k = array.length - 1; int x = 0; int y = 0; for(int i = 0; i < array.length; i++){ array[i] = (int)(Math.random()*16)-10; if(array[i] > 0){ x = array[i]; System.out.println(x); } } for(int i = 0; i < array.length / 2; i++){ int buf = array[i]; array[i] = array[k]; array[k] = buf; k--; } for(int i = 0; i < array.length; i++){ if(array[i] > 0){ y = x + array[i]; } } System.out.println(y + "!!!");