This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Could someone explain how to solve to this problem?  RSS feed

 
kenny gill
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have no idea. I'd really appreciate some insight on how to solve it:

How would you refer to the last element in array A declared as

int[] A = { 1, 3, -4, 7 };
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

or more general:
 
kenny gill
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


but what is it asking and how did you figure out that answer?
 
William P O'Sullivan
Ranch Hand
Posts: 859
Chrome IBM DB2 Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java arrays start at index 0, so in your example A[0] == 1

A.length returns the true length, in this case 4, so you must subtract 1 to get the last entry.

TIP: Be careful if length == 0, since you will then try to index A[-1] which will fail.

WP
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16026
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To learn what exactly arrays are and how they work, see Arrays in Oracle's Java Tutorials.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!