Java Lab: Middle Item

preview_player
Показать описание
----------------------------------------------------------------------------------------
Social media:
----------------------------------------------------------------------------------------

Code in comments
Рекомендации по теме
Комментарии
Автор

What if int[] userValues = new int[9];?

loganwright
Автор

Why do we add 1 to the arraylength? Why don't we subtract it?

trulytori
Автор

public class LabProgram {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int userValues[] = new int[10]; // declare array of 10 elements
int arrayLength = 0; // array length initialize with 0

for (int i = 0; i < 10; i++) { // loop to take input from user 9 times since it should not exceed 9 numbers
userValues[i] = scnr.nextInt(); // Each index stores a value that the user inputed
// The for loop is finally terminated when the user is finished typing 9 numbers.

if (userValues[i] == -1) { // if input is -1 in one of the indexes, then break the loop and assign array length
// Example:
// Input = 2 3 4 8 11 -1
// userValues[0] = 2
// userValues[1] = 3
// userValues[2] = 4
// userValues[3] = 8
// userValues[4] = 11
// userValues[5] = -1

arrayLength = i + 1;
// arrayLength = 6
scnr.close();
break;

}

if (i == 9 && userValues[i] != -1) { // if input is increases 9 then print too many inputs
// userValues[i] != -1 is needed in there so that the program does not confuse a negative as an input value
System.out.println("Too many inputs");
return;
}
}

int middleInteger = (arrayLength - 1) / 2; // find middle element
// In the example middleInteger = (6 - 1) / 2
// giving 2.5 but in java, the decimal is cut off to give integer --> 2

// print middle element
// userValues[2]
// As the code above shows, it equals 4
}
}

bassboostey