• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sort String list Alphabetically with compareTo method/if else statements, logic errors  RSS feed

 
Grant Callant
Greenhorn
Posts: 11
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi fellow Ranchers,

I've been working on this project for about 2 days now- I figured it wouldn't be this difficult, but here I am. *Disclaimer* this is for a class lab, so please do not give me solutions, but a few nudges in the right direction, would be extremely helpful! ;)- Just figured I would declare that openly.

I'm having trouble with sorting Strings- 3 strings inputted by user, and I would like to output them in alphabetical order. I've used the str.compareToIgnoreCase method, and then I've tried to loop them through a series of if/ else statements. Everything I've been able to find online (including the forums here) has suggested to use the Comparator class, or to put the strings into an array, and sort list- I really would like to stick with just the String class, and its methods please.

The program itself works and compiles, but I am getting logic errors that I have been unable to solve. I'm using IntelliJ Idea, and I've ran it through the built in debugger, about 100+ times (not exaggerating, lol) just to see what it's doing in particular scenarios. For instance, I can get c, a, b, to print out as a,b,c correctly, but a,b,c, will print out as b,a,c.

For me this is kind of like a Sudoku puzzle, or a Rubik's cube! Each time I fix one scenario, it breaks another one, so I don't know if there's a(logic) solution to fix all possible scenarios (abc, acb, bac etc... to all print abc) or if possibly I just need more if statements. I've only pasted in the area where I'm having problems (the if statements). I apologize for the length, but I'm a big fan of the "Next Line" syntax. Any help would be greatly appreciated!

Thank you.

(Note: please assume the non relevant content- import Scanner class, main method, etc... I didn't want to paste the entire program.)

 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would do the following:

1. Convert the input Strings into a List or an Array
2. Iterate over the array, take the first element and compare it against all the next element in the Array
3. If the comparison results in the first element being the smallest, I will collect that into another sorted collection
4. If the comparison fails, then I will continue until I have done it for all the elements
 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you can already see that your solution involves more lines of code for sorting just three Strings and it is not scalable meaning if you input another one, then you have to modify your entire if else. I would refrain from writing such code with those nested if else blocks. It becomes hard to read and maintain.
 
Grant Callant
Greenhorn
Posts: 11
1
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Joe,

I appreciate the response. I completely agree with you on the modularity and the scalability of using an array, and that is most certainly the preferred format. However, as I stated, my teacher is (his words) "drilling us with the String class" so that it is solidified, which I understand. He does not want us to use an array at this time- although as you stated, that would be the easiest and cleanest way to do it . Which I'm also guessing why most of the content available online gives instructions for just this sort of thing, with an array.

Thank you,

-Grant
 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I were to stick to your version of if else without using any Arrays, I would do the following. This is just an untested Pseudo-code!


 
Joe Harry
Ranch Hand
Posts: 10128
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Grant Callant wrote:Hi Joe,

I appreciate the response. I completely agree with you on the modularity and the scalability of using an array, and that is most certainly the preferred format. However, as I stated, my teacher is (his words) "drilling us with the String class" so that it is solidified, which I understand. He does not want us to use an array at this time- although as you stated, that would be the easiest and cleanest way to do it . Which I'm also guessing why most of the content available online gives instructions for just this sort of thing, with an array.

Thank you,

-Grant


Welcome to the Ranch!
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome again

There are all sorts of different ways to sort things. You can find lost of websites about sorting. This one has pictures. It also tells you the algorithms, and which is more efficient for large collections. The most inefficient sort method known is probably that called BogoSort. Bogo is short for bogus, so you never use it in real life.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Grant Callant wrote:I'm having trouble with sorting Strings...

And that's, I suspect, because you're trying to work out all the possible permutations of comparisons, when in fact you don't need to. You already have 6 variables: Your Strings as entered by your user and your three places to put them (small, big and biggest), so:

Step 1: Put the first two strings into small and big in the correct order (one check).

Now you only have the third one to deal with:
  • If it's >= big, put it in biggest.
  • If it's < small, move the other two over and put it in small.
  • Otherwise it must be >= small and < big, so move big to biggest and put it in big.
  • Three checks; job done.

    HIH

    Winston

    PS: I've broken up that last line because it was far too long, which makes the thread very difficult to read.
     
    Grant Callant
    Greenhorn
    Posts: 11
    1
    IntelliJ IDE Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ah that makes sense Winston. I think the trouble that I was having with that, was that I couldn't use any kind of boolean on the strings themselves, I could only use boolean on the compareTo int. I think I can figure out a way to implement yours though .

    Thank you also Joe for the example code- that helped to clarify and simplify what I've been trying to iterate for the last two days.

    I'll give both of those suggestions a go, and see if I can't implement them.

    (Sorry about the long line- I use Idea, and I have to make a conscious effort to return the line before the white margin. On Idea, the margin is like 120?ish, way over the limit... lol.).

    Thanks again for all of your help!

    Regards,

    -Grant
     
    Winston Gutkowski
    Bartender
    Posts: 10575
    66
    Eclipse IDE Hibernate Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Grant Callant wrote:Thanks again for all of your help!

    You're most welcome.

    And just a little tip: If you run into this sort of problem again, StopCoding (←click) and try clearing your mind. In fact, it's often not a bad idea to turn your computer OFF, so that you're forced to use paper and pencil.

    Winston
     
    Grant Callant
    Greenhorn
    Posts: 11
    1
    IntelliJ IDE Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Got it! Thanks to all of your help. I know I didn't do it exactly the best way possible, and I know my code's a little messy and inefficient, and it's not that I didn't want to code as efficiently as you advised, but I wanted to give myself some practice in formal logic and boolean. So, I went back and drafted it on paper first and then coded, messed with it a little, and it finally all works. I feel if Winston hadn't recommendation that I "Stop Coding" and draft it, I probably wouldn't have figured it out. So thank you Winston .

    Also, thanks for the nudge Joe- my code's not as pretty as yours, but I got the drift .

    If anyone's interested here's my *disclaimer* messy- albeit, now working code...



    Regards,

    -Grant

     
    Winston Gutkowski
    Bartender
    Posts: 10575
    66
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Grant Callant wrote:Got it! Thanks to all of your help. I know I didn't do it exactly the best way possible, and I know my code's a little messy and inefficient, and it's not that I didn't want to code as efficiently as you advised, but I wanted to give myself some practice in formal logic and boolean. So, I went back and drafted it on paper first and then coded, messed with it a little, and it finally all works.

    Very well done! And have a cow for posting your solution.

    Another tip for you: You can often help yourself out by breaking up a problem into separate methods (or even classes).

    Consider this solution that doesn't involve any "moving" of Strings. I've supplied it now to give you something to think about because you already have a solution that works:Do you see what's happened? By simply arranging things a bit better, I've been able to move most of the code that used to be in your main() method verbatim to methods that:
    (a) Do one (and ONLY one) thing.
    (b) Describe what they're doing.

    And wouldn't you say that main() looks much more readable now?

    I should add that the above is only ONE way to do it; there are tons of others. I only wrote it to show you how much nicer things can look if you break them up and give them good names. However, it's much harder to do if you simply start coding straight away.

    HIH

    Winston
     
    Grant Callant
    Greenhorn
    Posts: 11
    1
    IntelliJ IDE Java Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Hey, thanks for the cow! Yes, I certainly like your code much more than mine , that main method is really neat and succinct. I actually really appreciate you for posting it, as I've been able to use some aspects of your code here to apply to other projects.

    The breaking the code up into smaller segments (methods) is something I'm really working on. I noticed that you were able to get a lot of your methods to be void, so they were easy to implement into the main method. I've started using that technique any time I need to get data back into main, so I don't have to try to specify a return type.

    I also had been running into the "non-static content cannot be referenced in static..." for which I noticed you have an interesting way of dealing with . I actually started using that myself in a few places, making the current class the object of a Reference, and then you can call any methods inside of it.

    Thank you again.

    Regards,

    -Grant
     
    Winston Gutkowski
    Bartender
    Posts: 10575
    66
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Grant Callant wrote:Hey, thanks for the cow! Yes, I certainly like your code much more than mine , that main method is really neat and succinct. I actually really appreciate you for posting it, as I've been able to use some aspects of your code here to apply to other projects.

    Glad it helped. We like to encourage people to post their solutions because it helps other people (including us), understand the thought process. The "neatness" comes with practise - nothing more - but you have to be willing NOT to start coding straight away.

    I don't want to overload you too soon, but you might be interested in reading the Wikipedia article about coupling (in particular: loose coupling), because it's a very important aspect of writing good, flexible programs.

    In fact, some might argue that my variation is still too tightly coupled, because it relies on calling methods in a particular way; but the main point was to show you how to break stuff up while still keeping most of the same code.

    For more on this subject you might want to check out the WhatNotHow (←click) page; and also read up on the Single Responsibility Principle.

    The breaking the code up into smaller segments (methods) is something I'm really working on. I noticed that you were able to get a lot of your methods to be void, so they were easy to implement into the main method. I've started using that technique any time I need to get data back into main, so I don't have to try to specify a return type.

    That will generally have more to do with whether the method you're writing is a process or a function. To be honest, I tend to prefer functions - ie, methods that do return something - but that's because it's the way I think. As you'll discover, there's very rarely a "right" or "wrong" way to do things in programming - just usually "more or less flexible/readable" ("more" being preferable for both).

    I also had been running into the "non-static content cannot be referenced in static..." for which I noticed you have an interesting way of dealing with .

    Yes, that's a fairly common problem for beginners, because (I think)
    1. You're still looking at methods as just "pieces of code".
    2. You run into this problem early on, and so start writing all your methods as static because it "solves" the problem.
    In fact, other than main(), most of the methods you write should NOT be static.

    Remember, Java is an Object-Oriented language, not a Class-Oriented one.

    I actually started using that myself in a few places, making the current class the object of a Reference, and then you can call any methods inside of it.

    Great. And again, if you're interested, you can find an alternative (and much more generic) solution in MainIsAPain.

    Thank you again.

    You're most welcome. And good luck.

    And don't forget, whenever you run into a roadblock: StopCoding.

    Winston
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!