-2

Recently I have been working on a Java program. Today I have ran into an issue, where I would have to use values of a range of fields in a array. The length of the array is unknown, it is basically user input broken down into pieces. When I say I want to use the values of multiple fields in an array I mean something like that example from Ruby I am going to give you:

puts arr[1..10]

I can't seem to find the Java version of that thing.

I searched on the internet for the solution but I think I wrote the question wrong because it all led me to a tutorial how to make arrays.

Turamarth
  • 2,282
  • 4
  • 25
  • 31
  • and what are you supposed to do with those values? – Stultuske Jun 08 '23 at 11:48
  • You are looking for `Arrays.copyOfRange` – Jorn Jun 08 '23 at 11:49
  • @Stultuske I need to take them and put them into a single String. – smoowe2125 Jun 08 '23 at 11:49
  • iterate over them and apply String concatenation – Stultuske Jun 08 '23 at 11:49
  • @Jorn Thanks. I am going to try that right away. – smoowe2125 Jun 08 '23 at 11:49
  • 2
    Please include examples of input and expected output/product. Please include your attempt and highlight where it you are struggling. There is a germ of multiple questions here so it is unclear what part you actually need help with. Clear and concise questions produce better answers faster. – vsfDawg Jun 08 '23 at 12:10
  • @smoowe2125, so, that _Ruby_ code is saying, print out values 1 through 10 from _arr_? – Reilas Jun 10 '23 at 03:43
  • I think that the OP is asking how to do [array slicing](https://en.wikipedia.org/wiki/Array_slicing) in Java. The short answer is that you can't. Java doesn't support it. – Stephen C Jun 10 '23 at 04:03
  • But you >can< do something similar to slicing with `List.sublist`. And note that `Arrays.copyRangeOf` is NOT equivalent to slicing because it is creating a new array. Changing the copy doesn't change the original array. – Stephen C Jun 10 '23 at 04:14

1 Answers1

-1

There isn't a syntax for ranges, in Java.

You can utilize the Arrays#toString method, to print an array.

And, as @Jorn mentioned, you can use Arrays#copyOfRange to isolate the values.

The upper-bound value is exclusive.  So, you'll need to use 11.

int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 1, 11)));

Ouput

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Reilas
  • 3,297
  • 2
  • 4
  • 17