-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.

9
  • and what are you supposed to do with those values? Commented Jun 8, 2023 at 11:48
  • You are looking for Arrays.copyOfRange Commented Jun 8, 2023 at 11:49
  • @Stultuske I need to take them and put them into a single String. Commented Jun 8, 2023 at 11:49
  • iterate over them and apply String concatenation Commented Jun 8, 2023 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. Commented Jun 8, 2023 at 12:10

1 Answer 1

-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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.