1 2 Previous Next 26 Replies Latest reply: Jul 17, 2007 7:02 PM by 807605 RSS

    arrays in a program

    807605
      How can a program that uses arrays be changed into a class that can be used by other programs?
      for example this program:
      import java.util.Scanner;//working perfectly
      public class AmountToText     //Not taking credit for this
      {
      public static void main(String... args)
        {
          Scanner keyboard = new Scanner(System.in);
            System.out.print("enter whole amount  ONLY "); 
            //AmountofCheck sn = new Amou
            int[] amount = new int [1]; //can hold 1 elements p. 451
            amount[0] = keyboard.nextInt(); //in the position 0
            for (int n : amount)//was int
          {
            System.out.printf("%n%,d%n", n);
            System.out.printf("%s%n", AmountToText(n));
          }
        }//ends main 
        
        
        static final String[] units = { "", "one", "two", "three", "four",
                                        "five", "six", "seven", "eight", "nine" };
        static final String[] teens = { "ten", "eleven", "twelve", "thirteen",
                                        "fourteen", "fifteen", "sixteen",
                                        "seventeen", "eighteen", "nineteen" };
        static final String[] tens =  { "twenty", "thirty", "forty", "fifty",
                                        "sixty", "seventy", "eighty", "ninety" };
        static final String[] mil =  { "", "thousand" };
        public static String AmountToText(int num)// numToWords=NumberToWordsMT 
              {
          if (num == 0)
          {
            return "cero";
          }
          StringBuilder sb = new StringBuilder();//var-length array has sequence of characters*concanates Good
          /*if (num < 0)
          {
            sb.append("Negative");
          }*/
          String numStr = String.valueOf(num).replaceFirst("^-", "");//replaces- w/nothing
          String[] parts = numStr.split("(?=(?:\\d\\d\\d)++$)");//split them in parts with 3 digits
          int mag = parts.length - 1;
          for (int i = 0; i <= mag; i++)
          {
            if (parsePart(parts, sb) && mag > 0 && i < 6)//6=mag
      {
      sb.append(" ").append(mil[mag - i]).append(",");
      }
      }
      return sb.toString();
      }

      /*************************************************/
      static boolean parsePart(String str, StringBuilder sb)
      {
      boolean notZeroes = false;
      int pos = 0; // pos=index
      char ch = (char)0;
      if (str.length() == 3 && (ch = str.charAt(pos++)) != '0')
      {                      //if it has 3 positions & is diff than 0
      ExtraSpace(sb); //invoke units and append hundred
      sb.append(units[ch - '0']).append(" hundred");//position 0=hundred
      notZeroes = true;
      }
      if (str.length() > 1 && (ch = str.charAt(pos++)) != '0')//>1&diff than 0
      {
      ExtraSpace(sb);
      notZeroes = true;
      if (ch == '1')//if position 1 has a 1
      {
      sb.append(teens[str.charAt(pos)]);//invoke teeens
      return notZeroes;
      }
      sb.append(tens[ch - '2']);//otherwise invoke tens
      }
      if (str.length() > 0 && (ch = str.charAt(pos)) != '0')
      {
      ExtraSpace(sb);//if it is in position 0
      sb.append(units[ch - '0']);//invoke units array
      notZeroes = true;
      }
      return notZeroes;
      }
      /*************************************************/
      static void ExtraSpace(StringBuilder sb)
      {
      if (sb.length() > 0)
      {
      sb.append(" ");
      }
      }

      }//ends the begining

        • 1. Re: arrays in a program
          807605
          Changed how? Please try to be clearer.
          • 2. Re: arrays in a program
            807605
            thank you for your prompt reply

            this program can be run by itself because it has the "main"
            How can this be changed to a class that can be used by other programs?
            meaning after I removed the line 6:
            public static void main(String... args)
            What other changes do I have to do to this program so that another program such as the following could call/invoke it?
            import java.util.Scanner;
            public class AmountofCheckTester//SerialNumberTester
            {
               public static void main(String[] args)
               {
                  //String dollar = "123.89"; // serial1-dollar
                      Scanner keyboard = new Scanner(System.in);
                      String dollar = "";
                    System.out.print("Enter DOLLAR amount (numbers only) $");
                  // Get a customer number from the user.
                  dollar = keyboard.nextLine();//customer=Amount=dollar
                      //Validate dollar
                      AmountofCheck sn = new AmountofCheck(dollar);
                      
                  if (sn.isValid())
                         {      
                           System.out.print(sn.getFirst() );
                  
                      
                                
                      
                      
                           System.out.println(" and " + sn.getSecond()+"/100");
                           }
                      else
                     System.out.println(dollar + " is invalid.");
                }
            }
            • 3. Re: arrays in a program
              807605
              It can be used by other programs whether it has a main or not
              • 4. Re: arrays in a program
                807605
                Really,
                My teacher didn't mention that...
                so how can I call it from the program called "AmountofCheck.java"
                and give it the "amount" located in the variable sn.getFirst()
                • 5. Re: arrays in a program
                  807605
                  Really,
                  My teacher didn't mention that...
                  so how can I call it from the program called
                  "AmountofCheck.java"
                  and give it the "amount" located in the variable
                  sn.getFirst()
                  the main method can be called like any other static method.
                  • 6. Re: arrays in a program
                    807605
                    Really,
                    My teacher didn't mention that...
                    so how can I call it from the program called
                    "AmountofCheck.java"
                    and give it the "amount" located in the variable
                    sn.getFirst()
                    the main method can be called like any other static
                    method.
                    Not that that's necessarily the way to get your class to work with other classes, of course.....
                    • 7. Re: arrays in a program
                      807605
                      import java.util.Scanner;
                      public class AmountofCheckTester//SerialNumberTester
                      {
                         public static void main(String[] args)
                         {
                            //String dollar = "123.89"; // serial1-dollar
                                Scanner keyboard = new Scanner(System.in);
                                String dollar = "";
                              System.out.print("Enter DOLLAR amount (numbers only) $");
                            // Get a customer number from the user.
                            dollar = keyboard.nextLine();//customer=Amount=dollar
                                //Validate dollar
                                AmountofCheck sn = new AmountofCheck(dollar);
                                
                            if (sn.isValid())
                                   {      
                                     System.out.print(sn.getFirst() );
                            
                                // WHAT SHOULD I TYPE HERE???
                                          
                                
                                
                                     System.out.println(" and " + sn.getSecond()+"/100");
                                     }
                                else
                               System.out.println(dollar + " is invalid.");
                          }
                      }
                      • 8. Re: arrays in a program
                        807605
                        Move all the code out of that main method, into another method. Don't make that method static. Then have your main method here create a new instance of the class, and invoke this shiny new method

                        Bingo. Although from looking at it, the method is too busy. But worry about that later!
                        • 9. Re: arrays in a program
                          807605
                          The previous program "AmountofCheckTester.java" test the following program:
                          but how can I call a program like the one called "AmountToText.java" that I posted above???
                          import java.util.StringTokenizer; 
                          public class AmountofCheck//
                          {
                             private String first;   // First group of characters
                             private String second;  // Second group of characters
                             private boolean valid;  // Flag indicating validity
                          
                             //*******************************************************
                             // The following constructor accepts a number as 
                             // its String argument. The argument is broken into     
                             // 2 groups and each group is validated.            
                             //*******************************************************
                             public AmountofCheck(String sn)
                             {
                                // Create a StringTokenizer and initialize
                                // it with a trimmed copy of sn. 
                                StringTokenizer st =
                                       new StringTokenizer(sn.trim(), ".");
                          
                                // Tokenize and validate.
                                if (st.countTokens() != 2)//This is the number of tokens 
                                   valid = false;
                                else
                                {
                                   first  = st.nextToken();   //1st part of amount
                                   second = st.nextToken();  //2nd part of amount
                                   validate();                           //invoking meth below     
                                }
                          
                             }
                          
                             //****************************************************
                             // The following method returns the valid field.     *
                             //****************************************************
                             public boolean isValid()
                             {
                                 return valid;
                             }
                          
                             //****************************************************
                             // The following method sets the valid field to true *
                             // if the serial number is valid. Otherwise it sets  *
                             // valid to false.                                   *
                             //****************************************************
                          
                             private void validate()//private
                             {
                                if (isFirstGroupValid() && isSecondGroupValid())         
                                          valid = true;
                                else
                                   valid = false;
                             }
                             //****************************************************
                             // The following method validates the first group of *
                             // characters. If the group is valid, it returns     *
                             // true. Otherwise it returns false.                 *
                             //****************************************************
                             private boolean isFirstGroupValid()
                             {
                                boolean groupGood = true;  // Flag
                                int i = 0;  // Loop control variable
                          
                                // Check the length of the 1st group.
                                if (first.length() >= 4)//was !=5
                                   groupGood = false;
                          
                                // See if each character is a Digit.
                                while (groupGood && i < first.length())
                                {
                                   if (!Character.isDigit(first.charAt(i)))
                                      groupGood = false;
                                   i++;
                                }
                          
                                return groupGood;
                             }
                          
                             //****************************************************
                             // The following method validates the second group   *
                             // of characters. If the group is valid, it returns  *
                             // true. Otherwise it returns false.                 *
                             //****************************************************
                          
                             private boolean isSecondGroupValid()
                             {
                                boolean groupGood = true; // Flag
                                int i = 0; // Loop control variable
                          
                                // Check the length of the group2.
                                if (second.length() != 2)
                                   groupGood = false;
                          
                                // See if each character is a digit.
                                while (groupGood && i < second.length())
                                {
                                   if (!Character.isDigit(second.charAt(i)))
                                      groupGood = false;
                                   i++;
                                }
                                    return groupGood;
                             }
                               
                               public String getFirst()
                               {
                                    return first;
                               }
                               
                               public String getSecond()
                               {
                                    return second;
                               }
                               
                          }
                          • 10. Re: arrays in a program
                            807605
                            I tried this but it give me an error??
                            What am I missing?

                            import java.util.Scanner;
                            public class AmountToTextTester
                            {                                                    
                            public static void main(String... args)//(String... args)
                              {
                                   Scanner keyboard = new Scanner(System.in);  
                                  int[] amount = new int[1]; // { 1, 23, 456, 7890, -1234567890 };
                                //validate amount
                                  System.out.print("enter WHOLE amount");
                                  amount[0] = keyboard.nextInt(); //in the position 0 
                                  
                                  //AmountToText sn = new AmountToText(amount);  
                                  
                                  for (int n : amount) 
                                {
                                  System.out.printf("%n%,d%n", n);
                                  System.out.printf("%s%n", AmountToTextTester(n));//Added Tester
                                }
                              }//ends main 
                            }//ends tester
                            • 11. Re: arrays in a program
                              807605
                              public class SomeOtherClass {
                              
                                public static void main(String[] args) {
                              
                                   AmountToText amountToText = new AmountToText(); 
                                   amountToText.invokeWhateverMethod();
                                }
                              }
                              Your teacher should be telling you this. If you're being formally taught, you shouldn't have to find this out from the forums. I'm criticising your teacher, not you, by the way!
                              • 12. Re: arrays in a program
                                807605
                                My Teacher... she means well, but...

                                anyways...
                                this is what I did and this is the error I am getting,
                                import java.util.Scanner;
                                public class AmountToTextTester
                                {                                                    
                                public static void main(String[] args)//(String... args)
                                  {
                                       AmountToText amountToText = new AmountToText();
                                     amountToText.parsePart();
                                     
                                     }//ends main 
                                }//ends tester
                                AmountToTextTester.java:7: parsePart(java.lang.String,java.lang.StringBuilder) in AmountToText cannot be applied to ()
                                     amountToText.parsePart();
                                Is AmountToText.java suppose to look like this? Or did I do it all wrong?


                                import java.util.Scanner;//working perfectly
                                public class AmountToText//Not taking credit for this
                                {
                                /*public static void main(String... args)
                                  {
                                    Scanner keyboard = new Scanner(System.in);
                                      System.out.print("enter whole amount  ONLY "); 
                                      //AmountofCheck sn = new Amou
                                      int[] amount = new int [1]; //can hold 1 elements p. 451
                                      amount[0] = keyboard.nextInt(); //in the position 0
                                      for (int n : amount)//was int
                                    {
                                      System.out.printf("%n%,d%n", n);
                                      System.out.printf("%s%n", AmountToText(n));
                                    }
                                  }//ends main 
                                  */
                                  
                                  static final String[] units = { "", "one", "two", "three", "four",
                                                                  "five", "six", "seven", "eight", "nine" };
                                  static final String[] teens = { "ten", "eleven", "twelve", "thirteen",
                                                                  "fourteen", "fifteen", "sixteen",
                                                                  "seventeen", "eighteen", "nineteen" };
                                  static final String[] tens =  { "twenty", "thirty", "forty", "fifty",
                                                                  "sixty", "seventy", "eighty", "ninety" };
                                  static final String[] mil =  { "", "thousand" };
                                  public static String AmountToText(int num)// numToWords=NumberToWordsMT 
                                        {
                                    if (num == 0)
                                    {
                                      return "cero";
                                    }
                                    StringBuilder sb = new StringBuilder();//var-length array has sequence of characters*concanates Good
                                    /*if (num < 0)
                                    {
                                      sb.append("Negative");
                                    }*/
                                    String numStr = String.valueOf(num).replaceFirst("^-", "");//replaces- w/nothing
                                    String[] parts = numStr.split("(?=(?:\\d\\d\\d)++$)");//split them in parts with 3 digits
                                    int mag = parts.length - 1;
                                    for (int i = 0; i <= mag; i++)
                                    {
                                      if (parsePart(parts, sb) && mag > 0 && i < 6)//6=mag
                                {
                                sb.append(" ").append(mil[mag - i]).append(",");
                                }
                                }
                                return sb.toString();
                                }

                                /*************************************************/
                                static boolean parsePart(String str, StringBuilder sb)
                                {
                                boolean notZeroes = false;
                                int pos = 0; // pos=index
                                char ch = (char)0;
                                if (str.length() == 3 && (ch = str.charAt(pos++)) != '0')
                                {                      //if it has 3 positions & is diff than 0
                                ExtraSpace(sb); //invoke units and append hundred
                                sb.append(units[ch - '0']).append(" hundred");//position 0=hundred
                                notZeroes = true;
                                }
                                if (str.length() > 1 && (ch = str.charAt(pos++)) != '0')//>1&diff than 0
                                {
                                ExtraSpace(sb);
                                notZeroes = true;
                                if (ch == '1')//if position 1 has a 1
                                {
                                sb.append(teens[str.charAt(pos)]);//invoke teeens
                                return notZeroes;
                                }
                                sb.append(tens[ch - '2']);//otherwise invoke tens
                                }
                                if (str.length() > 0 && (ch = str.charAt(pos)) != '0')
                                {
                                ExtraSpace(sb);//if it is in position 0
                                sb.append(units[ch - '0']);//invoke units array
                                notZeroes = true;
                                }
                                return notZeroes;
                                }
                                /*************************************************/
                                static void ExtraSpace(StringBuilder sb)
                                {
                                if (sb.length() > 0)
                                {
                                sb.append(" ");
                                }
                                }

                                }//ends the begining

                                • 13. Re: arrays in a program
                                  807605
                                  Well, your parsePart method takes 2 arguments, you have to supply them. I question the wisdom of passing it a StringBuilder, though. If it needs a StringBuilder to do it's work, it can get one itself. Maybe it should return a string, if that's what you want out of it. There's a fair amount wrong with the code, to be honest, but it would take some time to go through it, and your best bet - and quickest option - is to throw it all out and start again. No, really. Write down what you want it to do, in very simple terms. Don't be tempted to sum it all up in one convoluted sentence, be simplistic. You should then have a good start of a design
                                  • 14. Re: arrays in a program
                                    807605
                                    oh, no!!
                                    Don't tell me that.
                                    I wouldn't be able to finish it in time to turn it in.
                                    the program works fine as long as it is not being called by another method. it does this:

                                    enter whole amount  ONLY 678
                                    
                                    678
                                    six hundred seventy eight
                                    The problem is trying to call it from other program
                                    1 2 Previous Next