Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Strings in Java

  • 14-11-2012 3:21pm
    #1
    Closed Accounts Posts: 3,249 ✭✭✭


    Trying to see if the characters in a word are alphabetical and if so increase the value of a variable.

    This is the code I have.
    				for (index = 0; index <= word.length() -1; index ++)
    					{
    						if (word.charAt(index) >='a' && word.charAt(index) <= 'Z')
    							{
    								letterCount ++;
    							}
    					}
    				if (letterCount == word.length())
    					{
    						numberOfWords ++;
    					}
    

    Tested it with valid words but its not increasing the value of numberOfWords. Just keeps leaving me with 0. What am I doing wrong here ?


Comments

  • Registered Users, Registered Users 2 Posts: 30 fouga


    Scioch wrote: »
    Trying to see if the characters in a word are alphabetical and if so increase the value of a variable.

    This is the code I have.
                    for (index = 0; index <= word.length() -1; index ++)
                        {
                            if (word.charAt(index) >='a' && word.charAt(index) <= 'Z')
                                {
                                    letterCount ++;
                                }
                        }
                    if (letterCount == word.length())
                        {
                            numberOfWords ++;
                        }
    
    Tested it with valid words but its not increasing the value of numberOfWords. Just keeps leaving me with 0. What am I doing wrong here ?

    you are so lucky, I am going through a java manual now. Here is a program that will put a string of names in alphabetical order, it might help you


    import java.util.*;

    public class Name {
    public static void main(String[] args) {

    String names[] = { "Lauren", "Audrina", "Heidi", "Whitney", "Stephanie", "Spencer", "Lisa", "Brody", "Frankie",
    "Holly", "Jordan", "Brian", "Jason" };


    System.out.println("The original order:");

    for (int i = 0; i < names.length; i++)
    {
    System.out.print(i + " : " + names + " " );
    }
    Arrays.sort(names);
    System.out.println("\nThe new order:");

    for (int i = 0; i < names.length; i++)
    {
    System.out.print(i + " : " + names + " " );
    }
    System.out.println();
    }
    }

    This gives the following output when its run

    The original order:
    0 : Lauren 1 : Audrina 2 : Heidi 3 : Whitney 4 : Stephanie 5 : Spencer 6 : Lisa 7 : Brody 8 : Frankie 9 : Holly 10 : Jordan 11 : Brian 12 : Jason
    The new order:
    0 : Audrina 1 : Brian 2 : Brody 3 : Frankie 4 : Heidi 5 : Holly 6 : Jason 7 : Jordan 8 : Lauren 9 : Lisa 10 : Spencer 11 : Stephanie 12 : Whitney


    PS im only new to this but look at this line

    "if (word.charAt(index) >='a' && word.charAt(index)"

    the && should be +, i dont think java uses &&, but i could be wrong

    Hope it helps


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    Thanks for the reply, but thats a bit more advanced than I currently am or need. This is a basic thing to return how many words contain alpha characters. For example if the input was "I'm useless at programming" it would return a value of 3 as "I'm" contains a non alphabetical character.

    I have the rest of the code working but just cant seem to count the bloody things.


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,110 Mod ✭✭✭✭Tar.Aldarion


    Where are you initialising the variable, sure stick in all the code


  • Registered Users, Registered Users 2 Posts: 9 mowgli


    Hi Scioch,

    I don't usually post here, but noticed your thread on the main page and being bored fired up notepad, is this along the lines of what you're looking for:
    public class Test {
        public static void main(String[] args) {
            if(args.length > 0) {
                System.out.println("Counting alphabetical words in: [" + args[0] + "]");
    
                int totalAlpha = 0;
                String[] words = args[0].split(" ");
                for(String word: words) {
                    if(isAlpha(word)) {
                        ++totalAlpha;
                    }
                }
                System.out.println("Total alphabetical words: [" + totalAlpha + "]");
            }
            else {
                System.out.println("Prints the number of alphabetical words\nUsage:\njava Test <\"words\">");
            }
        }
    
        public static boolean isAlpha(String word) {
            for(int i = 0; i < word.length(); ++i) {
                if(!Character.isLetter(word.charAt(i))) {
                    return false;
                }
            }
            return true;
        }
    }
    


  • Closed Accounts Posts: 2,766 ✭✭✭juan.kerr


    letterCount should be initialized before the for loop rather than before the while loop. That way is starts at zero for each new word.

    The fact that numberOfWords is always zero suggests there is at least one more issue (since the current approach should match for the first word).

    Not sure of your background but I would consider using StringTokeniser (or similar) to split into words and Regular Expression to match the characters.

    Also when testing try with a single word first, then try two words, three words etc.


  • Advertisement
  • Moderators, Music Moderators Posts: 8,490 Mod ✭✭✭✭Fluorescence


    Pretty simple. You're checking to see if the value is between 'a' and 'Z' - if you look at an ascii table you'll see that caps come first, and then there's a few random characters before the lowercase letters.

    I'd put in:
    if ((word.charAt(index) >= 'A' && word.charAt(index) <= 'Z') || (word.charAt(index) >= 'a' && word.charAt(index) <= 'z')){
    etc etc
    }

    Hope this helps :)


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    juan.kerr wrote: »
    letterCount should be initialized before the for loop rather than before the while loop. That way is starts at zero for each new word.

    The fact that numberOfWords is always zero suggests there is at least one more issue (since the current approach should match for the first word).

    Not sure of your background but I would consider using StringTokeniser (or similar) to split into words and Regular Expression to match the characters.

    Also when testing try with a single word first, then try two words, three words etc.

    Good spot on the letterCount. Fixed that. The word is being printed. I can see its right. Its going into the loop and going through the right amount of iterations.

    So even it there was still problems I should get something shouldnt I ?

    And I dont have any background, this is all new to me and I have no idea what StrngTokeniser is . Basically all I need is to figure out how to correctly code the approach I'm taking (isolate the word by finding space and taking substring and check individual characters) as I believe its whats expected.


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    Pretty simple. You're checking to see if the value is between 'a' and 'Z' - if you look at an ascii table you'll see that caps come first, and then there's a few random characters before the lowercase letters.

    I'd put in:
    if ((word.charAt(index) >= 'A' && word.charAt(index) <= 'Z') || (word.charAt(index) >= 'a' && word.charAt(index) <= 'z')){
    etc etc
    }

    Hope this helps :)

    That was it all right. Thank you. So simple. Yet it never even entered my head that the condition was wrong. Hours and hours I've been at that. :o

    Any idea why the third word isnt going into the loop ?


  • Closed Accounts Posts: 2,766 ✭✭✭juan.kerr


    Scioch wrote: »
    That was it all right. Thank you. So simple. Yet it never even entered my head that the condition was wrong. Hours and hours I've been at that. :o

    Any idea why the third word isnt going into the loop ?

    I haven't run the code, but try:

    for (int index = 0; index <= word.length() -1; index ++)

    Also try outputting each character processed in the for loop.


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    juan.kerr wrote: »
    I haven't run the code, but try:

    for (int index = 0; index <= word.length() -1; index ++)

    Also try outputting each character processed in the for loop.

    Index is initialised earlier, so shoudlnt be a problem. The loop is working fine too, I output the results at each stage and they are all fine for the other words. But the third word just gets printed after its found and somehow avoids the loop.


  • Advertisement
  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    Actually its not the third word at all, its the second last word. It seems to be going to the last word before running the previous one through the loop. The plot thickens !!


  • Moderators, Music Moderators Posts: 8,490 Mod ✭✭✭✭Fluorescence


    Scioch wrote: »
    Actually its not the third word at all, its the second last word. It seems to be going to the last word before running the previous one through the loop. The plot thickens !!

    I'd guess that's because of your qualifier:

    for (index = 0; index <= word.length() -1; index ++)

    Try this:

    for (index = 0; index < word.length(); index ++)

    But I'm not entirely certain of it, and java isn't working properly on my machine at the moment so I can't test for you.


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    I'd guess that's because of your qualifier:

    for (index = 0; index <= word.length() -1; index ++)

    Try this:

    for (index = 0; index < word.length(); index ++)

    But I'm not entirely certain of it, and java isn't working properly on my machine at the moment so I can't test for you.

    I'm pretty sure its something to do with where I have that condition (If index of space == -1). Its finding that and moving on before finishing the rest of the string. But if I move it up I cant get the last word out, I can either get all but the second last or all but the last depending on where I have that if statement. I guess the sequence is out of whack.


  • Closed Accounts Posts: 2,766 ✭✭✭juan.kerr


    Scioch wrote: »
    I'm pretty sure its something to do with where I have that condition (If index of space == -1). Its finding that and moving on before finishing the rest of the string. But if I move it up I cant get the last word out, I can either get all but the second last or all but the last depending on where I have that if statement. I guess the sequence is out of whack.

    I would replace all the logic you have to split into words with the earlier suggestion from mowgli:

    String[] words = stringInput.split(" ");
    for(String word: words) {
    //Do something with word
    }


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    juan.kerr wrote: »
    I would replace all the logic you have to split into words with the earlier suggestion from mowgli:

    String[] words = stringInput.split(" ");
    for(String word: words) {
    //Do something with word
    }

    Probably isnt the best approach but I'm so close to having it working right. Cant go back to square one now.


  • Closed Accounts Posts: 2,766 ✭✭✭juan.kerr


    Scioch wrote: »
    Probably isnt the best approach but I'm so close to having it working right. Cant go back to square one now.

    The problem with your current approach is that you probably won't have covered all the test cases even when it appears that it is working.

    What if the first word is 1 letter or the last word is 1 letter. Will these break the logic?


  • Moderators, Science, Health & Environment Moderators, Social & Fun Moderators, Society & Culture Moderators Posts: 60,110 Mod ✭✭✭✭Tar.Aldarion


    I'd guess that's because of your qualifier:

    for (index = 0; index <= word.length() -1; index ++)

    Try this:

    for (index = 0; index < word.length(); index ++)

    But I'm not entirely certain of it, and java isn't working properly on my machine at the moment so I can't test for you.

    Nah i think he has that right, he would get an index out of range that way I think. Might need to fire up the aul IDE if i get a chance.
    EDIT: ah no, i think that would just give the same error actually. Wrong amount of words.

    Probably isnt the best approach but I'm so close to having it working right. Cant go back to square one now.

    Dont be afraid to learn something else, and take a little longer now. It will save you time in the long run.


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    Dont be afraid to learn something else, and take a little longer now. It will save you time in the long run.

    I'm not, I've just spent a lot of time on this approach and if I scrap it in favour of an easier one without actually knowing where I went wrong I'll probably meet a similar end the next time I have to do something like this. I re-started this particular one several times but always ended up in the same hole.

    Plus that other approach makes no sense to me, I'm working off college notes and what I'm using is all part of what we learned. Dont want to wander too far away from the stuff we've been given to solve these problems.


  • Closed Accounts Posts: 2,766 ✭✭✭juan.kerr


    While we see your point, the issue with your spaghetti code is that it is difficult to read, maintain, test and is currently not functioning as expected.

    If you were one of my developers I'd have you replace the logic because I wouldn't trust that it will function as expected in all possible scenarios.

    A key thing to learn as a developer is not to re-invent the wheel. If something similar exists already in core java classes then the chances are it has been well tested and well documented so can be safely used.

    There's no benefit to tweaking code that is poorly written to start with (no offence meant).


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    Solved the problem but I'm sure there's a better solution.

    I set the condition of the while loop to an exit mechanism while(exit != 0). Then in the if statement that is true when the index of the next space is out of bounds I set exit = 0. So I'm not relying on the index of the space to both exit the loop AND get the last word.

    Might not be pretty but got the job done.


  • Advertisement
  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    juan.kerr wrote: »
    While we see your point, the issue with your spaghetti code is that it is difficult to read, maintain, test and is currently not functioning as expected.

    If you were one of my developers I'd have you replace the logic because I wouldn't trust that it will function as expected in all possible scenarios.

    A key thing to learn as a developer is not to re-invent the wheel. If something similar exists already in core java classes then the chances are it has been well tested and well documented so can be safely used.

    There's no benefit to tweaking code that is poorly written to start with (no offence meant).

    No offence taken but as I said previously I'm limiting myself to what I've been taught in the course. I'm sure I wont win any prizes but I'm not a developer looking for the most efficient way to do something. I'm a student trying to learn how to do these things. I have to work with the tools I've been given.


  • Closed Accounts Posts: 3,249 ✭✭✭Scioch


    Thanks for the help everyone.


Advertisement