Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Could someone explain how to solve to this problem?

 
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
Saloon Keeper
Posts: 15272
37
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic