Page 2 of 2 First 12
  • Jump to page:
    #16
  1. No Profile Picture
    rebel with a cause
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2004
    Location
    The Batsh!t Crazy State.
    Posts
    5,817
    Rep Power
    3462
    Be proud of yourself it looks good so far.

    To answer your question:
    You want your end loop condition to be what you're using to see if it's right. So the loop ends when the input is right.
    Code:
    boolean right = false;
    while (right) {
      //enter word1:
      if (word1.length() <= 37) right = true;
    }
    Dear God. What is it like in your funny little brains? It must be so boring.
  2. #17
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Feb 2004
    Location
    Mobile, Alabama
    Posts
    4,023
    Rep Power
    1286
    Originally Posted by mvantuyl
    Actually, 'while' is a reserved word, but 'While' isn't. (But it still isn't a good idea to use 'While' as a class name)
    True, I didn't catch that. Sorry for the mistake.
  4. #18
  5. No Profile Picture
    rebel with a cause
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2004
    Location
    The Batsh!t Crazy State.
    Posts
    5,817
    Rep Power
    3462
    Something else I noticed:
    You've got a stray while statement at the end there. Were you going for a do while loop? If so it's really not necessary.
    Dear God. What is it like in your funny little brains? It must be so boring.
  6. #19
  7. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    WDSMIA
    Posts
    10,135
    Rep Power
    5054
    You want your end loop condition to be what you're using to see if it's right. So the loop ends when the input is right.
    It's never too soon to talk about design and/or refactoring. I generally like to break methods up into fairly atomic units of work. Again, once you have a decent algorithm, the code practically writes itself. Here's an example:

    Pseudocode:
    1) Ask the user for a word
    2) Ask the user for another word
    3) Display the words

    That's the basic idea of the program. We'll see that each step has its own set of requirements, but let's just start with this algorithm of program flow.

    Java Code:
    public class Foo {    
     
        private Foo() { } // prevent instantiation
     
        public static void main(String[] args) throws Exception {
            new Foo().go();        
        }
     
        void go() {
            String firstWord  = getWordFromUser();
            String secondWord = getWordFromUser();
            displayWords(firstWord, secondWord);
        }
     
    }


    Okay, this obviously won't compile (the methods aren't defined), but I'm not too worried about it. This pretty much covers the main program, right? Now, we just need to define those methods. We'll write some basic methods as "stubs", just to get a working program...

    Java Code:
     
        private String getWordFromUser() {
            return "something"; 
        }
     
        private void displayWords(String first, String second) {
            System.out.println("first: " + first + "\nsecond: " + second);
        }


    Okay, this compiles and runs, so we can see that we've got a working skeleton. Let's tackle the next small piece: user input. Once again, let's write up our algorithm in pseudocode:

    1) Get some input from the user
    2) While the input is invalid
    2a) Notify user of the error
    2b) Try to get good input

    Translated to Java, we get the following for our getWordFromUser() method:

    Java Code:
        private String getWordFromUser() {
            String input = getStringInput();
            while(isTooLong(input)) {
                notifyUserStringTooLong();
                input = getStringInput();
            }
            return input;
        }


    Again, we've got more undefined methods, so let's stub it out...

    Java Code:
        private String getStringInput() {
            return "foo";
        }
     
        private boolean isTooLong(String input) {
            return false;
        }
     
        private void notifyUserStringTooLong() {
            //...
        }
     
        private void quit() {
            System.exit(0);
        }


    So now, we've got a compiling and running program...

    Java Code:
    public class Foo {    
     
        private Foo() { } // prevent instantiation
     
        public static void main(String[] args) throws Exception {
            new Foo().go();        
        }
     
        void go() {
            String firstWord  = getWordFromUser();
            String secondWord = getWordFromUser();
            displayWords(firstWord, secondWord);
        }
     
        private String getWordFromUser() {
            String input = getStringInput();
            while(isTooLong(input)) {
                notifyUserStringTooLong();
                input = getStringInput();
            }
            return input;
        }       
     
        private String getStringInput() {
            return "foo";
        }
     
        private boolean isTooLong(String input) {
            return false;
        }
     
        private void notifyUserStringTooLong() {
            //...
        }
     
        private void quit() {
            System.exit(0);
        }
     
        private void displayWords(String first, String second) {
            System.out.println("first:  " + first + "\nsecond: " + second);
        }
     
    }


    So now, we can go in and handle each small stub...

    Java Code:
        private String getStringInput() {
            String input = JOptionPane.showInputDialog("Please enter a word");
            if (input == null) quit();
            return input;
        }
     
        private boolean isTooLong(String input) {
            return input.length() > MAX_INPUT_LENGTH;
        }
     
        private void notifyUserStringTooLong() {
            JOptionPane.showMessageDialog(null,
                "Input can't be longer than " + MAX_INPUT_LENGTH + " characters");
        }
     
        private void quit() {
            System.exit(0);
        }


    You'll notice the MAX_INPUT_LENGTH variable. It's a constant I chose to define because I loathe Magic Numbers. So once I define all that, I've got another compilable, runnable class I can test....

    Java Code:
    import javax.swing.JOptionPane;
     
    public class Foo {  
     
        private final int MAX_INPUT_LENGTH = 37;
     
        private Foo() { } // prevent instantiation
     
        public static void main(String[] args) throws Exception {
            new Foo().go();        
        }
     
        void go() {
            String firstWord  = getWordFromUser();
            String secondWord = getWordFromUser();
            displayWords(firstWord, secondWord);
        }
     
        private String getWordFromUser() {
            String input = getStringInput();
            while(isTooLong(input)) {
                notifyUserStringTooLong();
                input = getStringInput();
            }
            return input;
        }       
     
        private String getStringInput() {
            String input = JOptionPane.showInputDialog("Please enter a word");
            if (input == null) quit();
            return input;
        }
     
        private boolean isTooLong(String input) {
            return input.length() > MAX_INPUT_LENGTH;
        }
     
        private void notifyUserStringTooLong() {
            JOptionPane.showMessageDialog(null,
                "Input can't be longer than " + MAX_INPUT_LENGTH + " characters");
        }
     
        private void quit() {
            System.exit(0);
        }
     
        private void displayWords(String first, String second) {
            System.out.println("first:  " + first + "\nsecond: " + second);
        }
     
    }


    Hopefully you're getting the idea here. Solve your problems by tackling one small thing at a time. Think of the algorithm first, then write code in a stepwise fashion. Test each little bit as you go. Hopefully this simple example will start you well on your way toward completing your program.

    Good luck!

    Comments on this post

    • Guelphdad agrees : In depth answers like this are why I love Dev Shed! Wonderful.
    • LynxLee agrees : Wow, I agree with Guelphdad.. and you too. :P
    • canadiancreed agrees : Very nice
    • tcjohans agrees : great
  8. #20
  9. Walrus Gramps
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2005
    Location
    San Antonio, Texas
    Posts
    1,229
    Rep Power
    620
    WOW!

    That post should be stickied and made required reading for anybody learning programming.
  10. #21
  11. No Profile Picture
    rebel with a cause
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    May 2004
    Location
    The Batsh!t Crazy State.
    Posts
    5,817
    Rep Power
    3462
    If I ever get off my lazy behind and do it. I plan on having a programming tutorial site with my methodology. Might even publish it into a book. "How to Program the Right Way"
    Dear God. What is it like in your funny little brains? It must be so boring.
  12. #22
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    19
    Rep Power
    0
    Ok I have tidied it up abit I think But I still cant seem to get it to loop back to the inputs if there is an error in the length of the word. I really appreciate the help so far aswell, it has giving me a much better understanding of programming.

    Code:
    import javax.swing.*;
     
     class Homework9 
     {
       public static void main (String args[]) 
    	{
    	  int length1, length2;
    	  //input a word  
    	  String input1 = JOptionPane.showInputDialog("Enter first word");
          length1 = input1.length();
    	  if (input1.length() > 37)
    	  
    	  //prints an error message if the length of word 1 exceeds 37 characters	    		    
    	  JOptionPane.showMessageDialog(null,"Error",
          "Error word length exceeds 37", JOptionPane.ERROR_MESSAGE);
          
          //input a second word      
          String input2 = JOptionPane.showInputDialog("Enter second word");
    	  length2 = input2.length();
    	  if (input2.length() > (38-length1))	    		    
    		    
    	  //prints an error message if the length of word 1 and word 2 exceeds 38 characters    
    	  JOptionPane.showMessageDialog(null,"Error total length of words exceeds 38 characters",
          "Error", JOptionPane.ERROR_MESSAGE);
                
          //how long is input1
    	  int i = input1.length();
    	  //print input 1
    	  System.out.print(input1);
          //keep printing dots till there is only room left for input 2
    	  while (i < (40 - input2.length())) 
    	  {
    	    System.out.print(".");
    		i++;
                 
          }
    		//print input 2
    	    System.out.println(input2);
    		 
    		
    		
    	}
    }

    Cheers.
  14. #23
  15. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    WDSMIA
    Posts
    10,135
    Rep Power
    5054
    Ok I have tidied it up abit I think
    Everything is still piled into the main method, and begs to be refactored. Each method should do one thing, and do it well. Don't make your main method work so hard...

    But I still cant seem to get it to loop back to the inputs if there is an error in the length of the word.
    Either you haven't yet developed an understanding of what the algorithm for such an action should be, or you don't understand how to translate that algorithm to Java. Either way, you haven't written your program to "loop back to the inputs"; you must tell the computer what you want it to do, and there's nothing in your example that says "keep trying to get input if it isn't correct". Please study the code I posted, especially the getWordFromUser() method.
    Last edited by Yawmark; November 16th, 2005 at 08:24 AM.
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"v\"ʲ\"vΤ\"".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  16. #24
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2005
    Posts
    19
    Rep Power
    0
    Sorted it, I was using if's instead of whiles and I have broken it down some. Thanks alot for the input guys, I like how you didnt just drop an answer to my question without trying to make me understand what it was I was trying to achieve. I will no doubt have many more questions as I try and gain a wider understanding of Java.

    Thanks again.

    Stephen

    Comments on this post

    • crownjewel82 agrees : Thanks for not being lazy and wanting help not handouts.
    • Yawmark agrees : Glad you're working on it. Your success is due, no doubt, to your regal first name... :)
    • gimp agrees
  18. #25
  19. Career Newbie
    Devshed Novice (500 - 999 posts)

    Join Date
    Dec 2005
    Location
    Klamath Falls, Oregon
    Posts
    643
    Rep Power
    12
    This topic is great!

    I acutally read the whole thing.

    I'm really getting into Java not with as much difficulty just because I have programmed before. I'm not so sure Java is the best language to start with.

    Years ago I used "Learn To Program Basic". Fun stuff.

    Then I went straight into REALbasic, now Java.

    Good luck.
Page 2 of 2 First 12
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo