0

I want to know what will be best to use if I have something like chapters with pages from-to - example:

Chapter 1, 0-10;
Chapter 2, 11-33;
Chapter 3, 54-90;
...

Now I want to get the chapter based on the on a page number, in example I input 60, and it should return Chapter 3.

How can I do this in JAVA?

Darko Petkovski
  • 3,892
  • 13
  • 53
  • 117

1 Answers1

-1

You could make a hash map of Integers that return a String for the chapter you are on

private void SimpleChapterHashmap(){
    HashMap<Integer, Integer> chapters = new HashMap<Integer, Integer>();
    for (int i = 0; i < 10; i++) {
        chapters.put(i, 1);
    }
    for (int i = 11; i < 33; i++) {
        chapters.put(i, 2);
    }
    for (int i = 34; i < 90; i++) {
        chapters.put(i, 3);
    }

    Log.d("CHAPTER", chapters.get(60));
}
Xjasz
  • 1,238
  • 1
  • 9
  • 21
  • Its just an example this isn't something that oracle needs. – Xjasz Mar 11 '15 at 14:38
  • @Xjasz See my comment above for a MUCH better, MUCH more efficient implementation which is already part of the Java API – Kon Mar 11 '15 at 14:48
  • Your link is no different other than using – Xjasz Mar 11 '15 at 14:51
  • I think the reason people are saying it's inefficient is not because you used `String` but because you stored an entry for every page rather than every chapter. All the other people commenting have assumed the `54` in the question was a typo, and that you could use a `TreeMap` to just store the last page number for each chapter. In fairness, your answer does answer the question as given. – Paul Boddington Mar 11 '15 at 15:03
  • I was only using a String to help him understand it a little better. Of course you can use integer,integer or even range,integer but that might make it harder for someone to understand. – Xjasz Mar 11 '15 at 15:06