-1

I have been trying to calculate the value of each letter within a string input by the user (firstname which is then transferred to firstname1 after conversion to lowercases) in order to then add the total to the sum of an int and a double (ageWeight).

I am facing issues with the for loop which does not seem to work (without it I get a final result which does not include the value of the string, but the code at least runs to the end) as I get an error in the console (Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8).

Eclipse does not give me any error that prevents me from running the codes, so I'm a bit confused as to where in the for loop (or its structure) am I wrong. I've been looking at all sorts of things online and can't get anywhere.

Here is my entire code (before you give a low score which may block me from asking questions, please note that I do not expect anyone to do my work for me, we just don't all have the same level of understanding):


        Scanner input = new Scanner(System.in);

        System.out.println("Please enter your firstname: ");
        String firstname = input.next();
        firstname.toLowerCase();
        String firstname1 = firstname.toLowerCase();

        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        int nameValue = alphabet.indexOf(firstname1);
        int name = 0;
            for (int i=0; i <= firstname1.length(); i++)
            {
                name = firstname1.charAt(i);
            }

        System.out.println("Please enter your age: ");
        int int1 = input.nextInt();

        System.out.println("Please enter your weight: ");
        double db = input.nextDouble();

        double ageWeight = (int1 + db);
        double total = ((ageWeight + name) +1);
        System.out.println(total);

    }
Jon
  • 19
  • 1
  • 5
  • 4
    `i <= firstname1.length()` -> `i < firstname1.length()` – UnholySheep Nov 23 '19 at 20:35
  • 1
    Your iteration starts from 0 to firstname1-1 of the length of the string. Your loop starts at i=0. So as UnholySheep answered already, you are not going to check i <= firstname1.length(). You are checking from 0 to the number before it. – tksilicon Nov 23 '19 at 20:39
  • Java is C-like and thus is *zero based*, meaning array/indexes count from zero and end with one less than the length. Hence, the terminating condition of the loop should be changed like this: `for (int i=0; i = firstname1.length(); i++)` – Bohemian Nov 23 '19 at 20:41
  • for (int i=0; i <= firstname1.length() -1 ; i++), also are you sure about name = firstname1.charAt(i); you will endup with the value of the last character (mybe it is += or something like that ) – phoenixstudio Nov 23 '19 at 20:41

1 Answers1

1

Note that array indices in Java (any most other languages) start at 0, not 1. This means that in your array of say n elements, indices range from 0 to n - 1.

However, with your current loop condition, i <= firstname1.length(), you will be trying to access firstname1[n] (in the loop's final iteration), which does not exist, hence the IndexOutOfBounds exception.

To fix, simply replace your loop condition with i < firstname1.length() (< instead of <=) and this should do the trick.

Anis R.
  • 6,656
  • 2
  • 15
  • 37
  • Thanks for the tips @Anis R. replacing ```<=``` by ```i < firstname1.length()``` deffo helped and I do not get any error now. However the result of the loop is odd and I can't seem to figure out why. I have in mind that A=0, B=1 ... Z=25. So I was planning on adding +1 (which I did not do yet but that's not the issue). I always put the same int (20) and double (40.5) so I know that whatever the result I need to remove 60.5 to check. If I input **a** in string I get **60.5**, if I input **aa** I get **157.5** (-60.5 = 97), if I put ***Jon*** I get 171.5 (-60.5 = 111). I can't make sense of it. – Jon Nov 24 '19 at 10:15
  • 1
    @Jon This is because you are converting a character (`firstname1.charAt(i)`) to an int (`name`). What will happen is that the int `name` will be assigned to **the ASCII value** of the character you give it. e.g. the ASCII value of lowercase `a` is 97, and the value of lowercase `n` is 110. – Anis R. Nov 24 '19 at 12:27
  • 1
    Also, in your loop, you are not adding to the value of `name`, you are just replacing the old value with a new one. So in the end, `name` will be equal to the ASCII value of the last character only. Did you mean to put `name += firstname1.charAt(i)` in your loop (`+=`, not `=`)? – Anis R. Nov 24 '19 at 12:29
  • thanks again for the response. I wanted to avoid using **ASCII Value** (probably because of my lack of knowledge) and instead get the value 1 for A, 2 for B, ... 26 for Z, hence why I have added the ```String alphabet = "abcdefghijklmnopqrstuvwxyz"; int nameValue = alphabet.indexOf(firstname1);``` . Regarding your last question, I'm meant to say that ```name``` is equal to the value of the firstname1 character, hoping it would add up values of all characters from the string as it goes through the input. I am definitely off track I feel. – Jon Nov 24 '19 at 16:25