0

I've got array like this

int[] array = {5, 100, 20, 66, 16};
    price = new int[] {5, 100, 20, 66, 16};
    for(int i = offset; i < price[price.length - readLength]; i++) {
        price[i] = price[i] * (discount / 100);
        System.out.println(price[i]);

    }

I need to get new array after this only with three numbers of the old array. How can I do it? I need after that something like this [100,20,66]

2
  • 1
    which three numbers? Any of them? Commented May 10, 2021 at 20:04
  • it seems strange that you are comparing indexes to prices ( i < price[whatever] ) Commented May 10, 2021 at 20:14

3 Answers 3

4

You could use Arrays.copyOfRange to get this:

price = Arrays.copyOfRange(array, 1, 4) and then you can do operations on each element.

Or you could get a new array from the original array using:

double[] discounted_price = 
    Arrays.stream(array,1,4).
                  mapToDouble(el ->el - el*(discount/100.0)).toArray();

You don't need to use a copy to pass to stream, you can specify, from, to in Arrays.stream itself.

And @WJS is correct that you might need to subtract price*discount from price depending on how you intend to use discount.

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

3 Comments

And how can I apply discount(in %) to this numbers in array?
@CogsMaster Did you see my answer?
IMHO a non functional solution would be clearer to an OP asking at this level. But I could be wrong of course.
4

Your code has some problems.

  • The following won't work unless price has been declared an array and it should be a double array since you probably want the result to be a floating point number.
   double[] price = new double[3];
  • This will be a problem unless discount is a double or float. Also, consider that if something costs $2 and the discount is 10% then the cost will be: 2.00 - (2.00 * .10). So you should change:
   price[i] = price[i] * (discount/100);

To

   price[i] = price[i] - (price[i] * (discount/100.));

To copy array you can either use a for loop or the Arrays.copyOfRange() method as already mentioned. If you want random values you have to do individual assignments. The for loop would look like:

int k = 0 ;
for (int i = 1; i < 4; i++) { // copies values at indices 1,2, and 3
  price[k++] = array[i];
}

Comments

1

Try to use:

Arrays.copyOfRange()

1 Comment

Helpful, but not detailed at all. Please show a full solution with explanation and possibly also links to the documentation. Read How to Answer. Your answer is low-quality.

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.