I have a sorted array of numbers with 10 elements, the user sets the index number and I need to output the number that is under this index.

public class ArrTest { public static class Array{ private int array[] = new int[10]; public void UnsortedArr(){ for (int i = 1; i < array.length; i++) { array[i] = (int) (Math.random() * 20); } for (int i : array) System.out.print(i + " "); } public void SortedArr(){ Arrays.sort(array); System.out.print("\n"); for (int i : array) System.out.print(i + " "); } public void ReturnValue(int retValue) { } } public static void main(String[] args) { Array arr = new Array(); arr.UnsortedArr(); arr.SortedArr(); System.out.println("\n Enter index: "); Scanner sc = new Scanner(System.in); int k = sc.nextInt(); arr.ReturnValue(k); } 
  • And what's wrong with your code? - Visman
  • As a rule, in programming, the numbering of everything (characters in a string, elements in an array, etc.) starts from 0. In Java, at the level of the language and standard libraries, all numbering is always from 0. You can, of course, only use in your arrays part of the array (for example, in the array of ten elements use only 9 pieces, from 1 to 9, ignoring zero, as in your code), but if you follow the generally accepted rules, then the probability of any misunderstandings and errors will be much lower. - m. vokhm
  • And still - in Java it is accepted to name methods from a small letter. Again, the language allows and with a large, but there is a so-called. Java Naming Convention, which, if you stick to it, reduces the likelihood of errors and confusion. - m. vokhm

2 answers 2

 System.out.print(array[retValue - 1]); 
  • And if the user thinks that the first element is zero) - user31238
  • At it (it?) The array is initialized, starting with 1. The zero element is ignored. - m. vokhm
  • @ m.vokhm, so he has a bug. After all, everything is output and sorted - together with 0. - Qwertiy
  • Corrected. Thank you very much. - Hanna Bond
  • @Qwertiy So! And not one :) But it's impossible to count for sure, because a girl (after all, she has :) the task still cannot clearly formulate. - m. vokhm
 public void ReturnValue(int retValue) { System.out.print(array[retValue]); }