1
public class IntArray {
    public static void main(String[] args) {
        int number [] = {5, 7, 30, 40,};
        int i;
        int product;
        int answer;
        for (i = 0; i < number.length; i++) {
            System.out.print(number[i] + " ");
            if (number[i] >= 10)
                product = number[i] * 2;
            answer = product;
            System.out.println(product);
        }
    }
}

Is it possible to multiply my array? What i really want is to have 10 elements but i tried 4 elements for trial and i want these elements to be multiplied by 2 whenever the element is greater than 10...

Thanks!

4

2 回答 2

4

Yes, you can do it. Since this is definitely a learning exercise, here are some hints at how to do it:

Your loop assigns the value number[i] * 2 to product, which gets discarded after each iteration. Instead of doing that, use number[i] *= 2; *, and remove the declaration of the product variable.

You can also discard the answer, because it is only assigned, and never used after that.


* That's a shortcut for number[i] = number[i] * 2;

于 2013-10-10T15:00:12.020 回答
0

Yes, you can do this.

In addition to dasblinkenlight's hints, here's one more for you.

You'll run into run-time errors depending on how big your numbers are. The int type can only handle numbers so big. If the number you're multiplying by 2 is more than half of this number, you either (a) won't get the result you want, or (b) the program will come to a screeching halt, because you're also storing the doubled number in an int. Consider how you'd get around this.

于 2013-10-10T15:07:25.930 回答