Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 19 of 19

Thread: help with this question

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default help with this question

    I am given a string "Hello World!"
    and an array, int[ ] scores = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8, 4,10};
    the scores should corresponds to letters in the alphabet a=1, b=3,c=3 ........
    this code should add the scores that correspond to the letters
    characters that are not letters should count as 0
    I need to print the string followed by the score of the String
    also if the letter lands on a position divisible by 4, the score of that letter is doubled
    as a hint it says to turn the String to lowercase
    this is what I have but I might be doing it completely wrong
    it compiles but then when it runs i get this message with a bunch of other lines that start with at:
    java.lang.StringIndexOutOfBoundsException: String index out of range: 12


     
    public class Question{
      public static void main(String args[] ){
     
        int count = 0;
        int b = 0;
        int[ ] scores = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
        String s = "Hello There!";
        s = s.toLowerCase();
        System.out.println(s);
        for(int i = 0; i<scores.length;i++)
        {
          for(int j =97; j<122; j++)
          {
            scores[i] = j;
            for(int k = 0; k<s.length();k++)
            {
              b = (int)(s.charAt(i));
              if( j == b)
              {
                if(k%4==0)
                {
                  scores[i] = scores[i]*2;
                }
     
                count = count + scores[i];
              }
            }
          }
        }
     
     
     
        System.out.println( s + " " + count);
      }
    }
    Last edited by dmanmeds; July 3rd, 2014 at 09:33 PM.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: help with this question

    I don't understand what in the heck you're trying to do, but this:

    s.charAt(i)

    can't work because i will become much bigger than the size of s.

    Rarely is a double-nested loop required. Perhaps some comments in your code would help explain what you're doing and why.

    Update:

    Okay, I stared at it a bit more and worked out what you're supposed to be doing. You didn't explain it very well. In future, you might just post the assignment verbatim, copied and pasted, if possible.

    The array of 'scores[]' contains 26 values so corresponds to the letters of the alphabet, a - z. Therefore, to add the elements of scores[], one must equate each character in the String to be scored to its position in the array, and add the elements for all characters. For example, the String "hello" would be:

    scores['h'] + scores['e'] + scores['l'] + scores['l'] + scores['o']

    There is a way to do what I've described above, and you should be able to work it out.

    Once you do that, you'll have to account for the last part: "also if the letter lands on a position divisible by 4, the score of that letter is doubled". Frankly, I wouldn't even mess with that in code. I'd simply double all score[] elements that are divisible by 4, but that may not be acceptable to your instructor.

    A double-nested loop is not required. In fact, you should be able to do it with a single loop.

    Good luck!

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    dmanmeds (July 4th, 2014)

  4. #3
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: help with this question

    sorry about the confusion. This is just one part of a whole big problem I have to do but assigning the letters to scores was something I was not sure how to do.
    I tried doing this but I still get an out of bounds error
    am i on the right track?

     
    public class Question{
      public static void main(String args[] ){
     
        int count = 0;
        int[ ] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
        String s = "Hello There!";
        s = s.toLowerCase();
        System.out.println(s);
         for(int  i = 0; i<s.length();i++){
          int a = score[s.charAt(i) - 97] ;
          count= count + a;
        }
        System.out.println(s + " " + count);
     
     
      }
    }
    Last edited by dmanmeds; July 4th, 2014 at 10:32 AM.

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: help with this question

    I still get an out of bounds error
    The index into an array needs to be from 0 to the array's length-1.
    The code needs to map the char values it gets into that range, for example: 'a' gives 0 and 'z' gives 25

    You can do math with char variables and values: 'a' + 2 = 'c' or 'b' - 1 = 'a'
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: help with this question

    Better. Add one or two more print statement to figure out what's going on. Your -97 offset for 'a' through 'z' is a good idea, but what happens when the loop gets to the space in the String?

    Oh, and why is the int variable 'a' required?

  7. #6
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: help with this question

    technically this works for adding the letters but it only works if there is no space between the words. When I put the spaces in between the words I get the out of bounds error. I tried accounting for the space but then i get this
    unexpected type
    required: variable
    found : value

    this works without any spaces
    import java.util.*;
    public class Question{
      public static void main(String args[] ){
     
        int count = 0;
        int[ ] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
        char[ ] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        String s = "Hello There!";
        s = s.toLowerCase();
        System.out.println(s);
        for(int  i = 0; i<s.length();i++){
          int a = score[s.charAt(i) - 'a'];
          count= count + a;
           }
              System.out.println(s + " " + count);
     
     
      }
    }

    this gets an the unexpected type error
    import java.util.*;
    public class Question{
      public static void main(String args[] ){
     
        int count = 0;
        int[ ] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
        char[ ] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        String s = "Hello There!";
        s = s.toLowerCase();
        System.out.println(s);
        for(int  i = 0; i<s.length();i++){
          int a = score[s.charAt(i) - 'a'];
          if( s.charAt(i) = " "){
            a = 0;}
          count= count + a;
           }
              System.out.println(s + " " + count);
     
     
      }
    }

  8. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: help with this question

    You can use an 'if' (or if/else) statement to filter characters outside 'a' - 'z'. This is a reasonable approach, since the instructions specifically address non-alpha characters differently.

  9. The Following User Says Thank You to GregBrannon For This Useful Post:

    dmanmeds (July 4th, 2014)

  10. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: help with this question

    Don't do it all in one line of code. Break it up into steps
    Validate the char
    if valid compute the index
    use the index

    edit: better order (as per Greg)
    If you don't understand my answer, don't ignore it, ask a question.

  11. The Following User Says Thank You to Norm For This Useful Post:

    dmanmeds (July 4th, 2014)

  12. #9
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: help with this question

    I got it to count the String with non letters.
    but when I add the if statement to try to double the value when the String is divisible by 4, it doesn't produce the correct answer
    I do not get why. I am multiplying a*2 if the length of the String is divisible by 4 and a is the value of the letter that corresponds to the score in the array

    this runs correctly without the condition
    import java.util.*;
    public class Question{
      public static void main(String args[] ){
     
        int count = 0;
        int[ ] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
        char[ ] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        String s = "Hello there!";
        s = s.toLowerCase();
        System.out.println(s);
        for(int  i = 0; i<s.length();i++)
        {
          if((Character.isLetter(s.charAt(i))) == true)
          {
            int a = score[s.charAt(i) - 'a'];
           count= count + a;
          }
     
        }
     
     
        System.out.println(s + " " + count);
     
     
      }
    }

    here i add the condition and get the wrong answer*
     
    import java.util.*;
    public class Question{
      public static void main(String args[] ){
     
        int count = 0;
        int[ ] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
        char[ ] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        String s = "Hello There!";
        s = s.toLowerCase();
        System.out.println(s);
        for(int  i = 0; i<s.length();i++)
        {
    // this tests to see if the symbol at the position of the String at i is a letter
          if((Character.isLetter(s.charAt(i))) == true)
          {
            int a = score[s.charAt(i) - 'a'];        
     // this is to test if the length of the String is divisible  by 4 with remainder of 0
            if( s.length() % 4 == 0) 
           {
    // if the above condition is true then multiply the score corresponding to the letter by 2        
            a = a*2;
            }
     
           count= count + a;
          }
     
        }
     
     
        System.out.println(s + " " + count);
     
     
      }
    }
    Last edited by dmanmeds; July 4th, 2014 at 07:07 PM.

  13. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: help with this question

    Please add some comments to the code describing what the statements are trying to do.
    For example, what is this statement for:
    if( s.length() % 4 == 0){
    If you don't understand my answer, don't ignore it, ask a question.

  14. #11
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: help with this question

    I have updated it with some comments. Hope it clarifies what I was trying to do

  15. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: help with this question

    Why multiply by 2 if the String length is divisible by 4 inside of the for loop?

    Most of the comments are redundant.
    // this tests to see if the symbol at the position of the String at i is a letter
          if((Character.isLetter(s.charAt(i))) == true)
    Why do you care if the char is a letter?
    If you don't understand my answer, don't ignore it, ask a question.

  16. #13
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: help with this question

    this fixed the out of bounds error I had before, when a non letter (space, comma,ect) was trying to be scored. This way, when the for loop executes
    if it comes across a non letter then it will just ignore it ( count it as 0) and stay inbounds

  17. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: help with this question

    What is the problem with the code now?
    What does it print out now?
    What do you want it to print?
    If you don't understand my answer, don't ignore it, ask a question.

  18. #15
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: help with this question

    I need it to multiply the score by 2 , if the letter is at a position of the String that is divisible by 4 (0,4,8,16,...)
    in this case "Hello There!"
    'H' has a score of 4 but since 0 (the position of 'H' in the String) divided by 2 = 0 then it will have it's score multiplied by 2. Now 'H' will have a score of 8
    'e' has a score of 1 but is at position 8 so it will have it's score multiplied by 2

    right now what this code prints out is:
    hello there!
    hello there! 32

    also if i add another character ( increase the length of the string by 1), a comma for example, it just prints the regular score of the String without multiplying anything
    if the string is "Hello There!,"
    then this prints out:
    hello there!,
    hello there!, 16

    but I want it to print out:
    hello there!
    hello there! 22

  19. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: help with this question

    if the string is "Hello There!,"
    then this prints out:
    hello there!,
    hello there!, 16

    but I want it to print out:
    hello there!
    hello there! 22
    How is the value 22 computed? Can you show how it is is computed by doing it manually and typing in the values that would be added to the count?
    Show it in two or more columns:
    the char // the count

    the letter is at a position of the String that is divisible by 4 (
    Is that related to this code?
    if( s.length() % 4 == 0){
    If you don't understand my answer, don't ignore it, ask a question.

  20. #17
    Junior Member
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    6
    Thanked 1 Time in 1 Post

    Default Re: help with this question

    Yes " the letter is at a position of the String that is divisible by 4 "
    is related to this code
    if( s.length() % 4 == 0){

    String "Hello There!"
    gets turned into "hello there!" via s = s.toLowerCase();

    I'm not sure if this is what you were asking for

    position of String             0  1  2  3  4  5  6  7   8   9  10  11
    String                         h  e  l  l  o     t  h   e   r   e   !
    Score                          4  1  1  1  1  0  1  4   1   1   1   0
    *2 if pos divisible by 4       8           2            2
     
    count: 8+1= 9  9+1=10  10+1=11  11+2=13  13+1=14  14+4=18  18+2=20  20+1=21  21+1=22
    addition:          8+1+1+1+2+0+1+4+2+1+1+0 = 22


    never mind as I was writing this to explain to you I noticed that I should be dividing by i not s.length().
    Thanks!

     
    import java.util.*;
    public class Question{
      public static void main(String args[] ){
     
        int count = 0;
        int[ ] score = {1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10};
        char[ ] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        String s = "Hello There!";
        s = s.toLowerCase();
        System.out.println(s);
        for(int  i = 0; i<s.length();i++)
        {
          if((Character.isLetter(s.charAt(i))) == true)
          {
            int a = score[s.charAt(i) - 'a'];
            if( (i%4) == 0){
             a = a*2;
            }
     
           count= count + a;
          }
     
        }
     
     
        System.out.println(s + " " + count);
     
     
      }
    }
    Last edited by dmanmeds; July 4th, 2014 at 09:55 PM.

  21. The Following User Says Thank You to dmanmeds For This Useful Post:

    GregBrannon (July 5th, 2014)

  22. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: help with this question

    Try debugging the code by adding println() statements to print out the values as they are computed so you can see where the code is going wrong.
    If you don't understand my answer, don't ignore it, ask a question.

  23. #19
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: help with this question

    Post #17 is a great post! Thanks for thinking it through and sharing your thought process.

    I misinterpreted the meaning of this instruction:
    if the letter lands on a position divisible by 4, the score of that letter is doubled
    Your interpretation is probably correct, but I wonder about the index position, i = 0, being doubled. The if() condition i % 4 for i = 0 will be 0, so the score for that position doubled, but I wonder if that was the assignment's intent. Shifting i by 1 so that the first element is considered to be position 1 will then shift the rest of the doubled values by 1. Something for you to think about and decide the instructor's intent.

    Also, just a nit, this if() statement:

    if( (Character.isLetter(s.charAt(i))) == true )

    is the same as this more compact statement:

    if( Character.isLetter( s.charAt(i) ) )

Similar Threads

  1. Replies: 1
    Last Post: November 4th, 2013, 05:38 AM