0

How can I replace static value in an array? i want user's first input to be placed at first index.

Scanner input = new Scanner(System.in);

int[] arr = {0,0,0,0,0};

int seat = input.nextInt();

if(seat >=1 || seat <=5)

{

//how can i assign first input to index 0 permanently?

}
4
  • 4
    Permanently? You can't. All you can do is assign it, and then try not to assign it again. arr[0] = seat;. Commented Jul 26, 2019 at 13:19
  • Oh okay thanks. Can i ask one more thing? What loop(s) should best suit in a seat reservation program? Commented Jul 26, 2019 at 13:24
  • There is no way to answer that without more detail (and the amount of detail you'd need to provide is more than you can provide in a comment). Commented Jul 26, 2019 at 13:26
  • I think you meant && in your logical if. The way you have it written will always result in a true statement. Any number which is false with the first condition will be true with the second, and vise versa. Commented Jul 26, 2019 at 14:30

2 Answers 2

1

Arrays are mutable by definition. You can always assign a new value to any index arr[index] = newValue. You cannot make arrays read-only.

There are, however, read only lists that don't allow them to be altered after initialization, see for example java.util.Collections.unmodifiableList(<list>).

I don't know of any default implementation to lock a specific index of a List. For this you probably need your own implementation of the List interface.

Sign up to request clarification or add additional context in comments.

Comments

0

The elements of an array can not be made unchangeable or final.You could try checking for the value of array[0] every time the array is accessed and ensure that array[0] equals what you want it to by assigning it to a final variable (constant) each time your array operations are complete.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.