Friday, 15 July 2011

java - Why is less than 9, counting the 9? -



java - Why is less than 9, counting the 9? -

the java book have has various questions , 1 of them doing had listed in of book right answer, have written below. understand how works. why don't want utilize >=, how outputs when out of order, ect. don't understand why line requires <9 opposed <=9 or <10. know lastly number doesn't have loop because 1 before gets compared, if it's less 9 wouldn't stop before 9th element, making 10th element doesn't ever compared?

error code:

double[] scores = {2.5, 3.9, 4.8, 6.2, 6.2, 7.4, 7.9, 8.5, 8.5, 9.9}; (int = 1; <= 10; i++) if (scores[i] >= scores[i+1]) system.out.println(i + " , " + (i + 1) + " elements of score out of order.");

correct code:

double[] scores = {2.5, 3.9, 4.8, 6.2, 6.2, 7.4, 7.9, 8.5, 8.5, 9.9}; (int = 1; < 9; i++) if (scores[i] > scores[i+1]) system.out.println(i + " , " + (i + 1) + " elements of score out of order.");

edit: question is: next suppose ensure elements of scores in non-decreasing order. however, there errors in code. find , right errors.

remember indexes start @ 0. there 10 elements in list. means indexes range 0-9.

you accessing i , i+1 element. in for loop when i 8, looking @ items @ index 8 , 9. if allow loop go 9, seek access elements @ index 9 , 10 , indexoutofboundsexception.

java arrays

No comments:

Post a Comment