Results 1 to 10 of 10

Thread: Java Programming Help     submit to reddit submit to twitter

  1. #1
    Pens win! Pens Win!!! PENS WIN!!!!!
    Join Date
    Jul 2008
    Posts
    8,637
    BG Level
    8

    Java Programming Help

    Hey all. I'm having trouble completing a programming assignemnt. Been working on it for a while and not sure how to go on.

    The assignemnt, just for reference:



    Due: 9/19

    Write a class, called letterPrint, for printing a letter as a 7x5 grid of either spaces or asterisks (*). The letter is made up of a list of thirty-five 1's and 0's, which will be stored in an array representing the letter. This will be the only instance variable of the class.

    For example, the input for letter I would look like this:

    01110001000010000100001000010001110

    reading this input, your program will output a 1 as a * and a 0 as a space. So, the output will look like:

    ***
    *
    *
    *
    *
    *
    ***

    As you have noticed, after every 5 elements is printed, you will print a new line to get the output the way it looks like, an I.

    Write the following methods:
    - A constructor with one parameter, which is an array of thirty-five 0's or 1's. This is the only instance variable for your class. Make sure to enforce the constraint of only 0's and 1's.
    - Accessor, and equals methods
    - A method for printing out the letter (like the example)

    As always, you will need to write a tester to test all these methods.



    So far, the code I have is this:

    Code:
    import java.util.ArrayList;
    
    public class letterPrint
    {
      private String[] list;
      private String[][] display;
      private static final int ROWS= 7;
      private static final int COLUMNS =5;
      public letterPrint()
      {
        list= new String[35];
      }
      
      public void addValue(int j)
      {
        display = new String[ROWS][COLUMNS];
        for ( int i = 0 ; i < ROWS; i++ )
        {
          for ( int h = 0 ; h < COLUMNS; h++ )
            System.out.print(display[i][h] = " " );        
          if (j == 1)
            list[i] = "*";
          if(j == 0)
            list[i] = " ";
        }
      }
      
      
      
      
      public String[][] printArray()
      {
        return display;
      }
      
    }
    Code:
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class letterPrintTester
    {
      public static void main(String[] args)
      {
        Scanner in = new Scanner(System.in);
        letterPrint test= new letterPrint();
        System.out.println("Please enter 35 1's or 0's");
        for(int i= 0; i < 35; i++)
        {
           int myList = in.nextInt();
           test.addValue(myList);
                  
           if (i == 29)
             System.out.println("5 more inputs");
        }
           System.out.println(test.printArray());
        }
      
      
    }
    I'm having trouble implementing the information acquired from the user into the 2d array and then printing it. I have it stored in the 1d array, but I'm not sure how to get it to transfer to the 2d array.

    I know I have more then one isntance variable (and not following directions) but I want to see if I can do it with the ones I have. And I know I'm hard coding in some spots (I'll change that later).

    If someone could help, that would be greatly appreciated.

    I'm putting my flame shield up for anyone that does decide to flame me.

  2. #2
    Ridill
    Join Date
    Feb 2006
    Posts
    11,977
    BG Level
    9

    Code:
    String input = "01110001000010000100001000010001110";
    String output = "";
    
    for (int i=0; i<input.length() / 5 - 1; i++) {
      output += input.substring(i*5, (i + 1)*5 - 1).replace('0', ' ').replace('1', '*') + '\n';
    }
    
    System.out.println(output);
    Above should do the problem, now to add the constructor, accessor, equals, etc.

  3. #3
    Pens win! Pens Win!!! PENS WIN!!!!!
    Join Date
    Jul 2008
    Posts
    8,637
    BG Level
    8

    The thing is it's not always going to be an I. Whatever the user inputs is what is going to be displayed. So I don't think I can have the String input= ".." there. : (

  4. #4
    Ridill
    Join Date
    Feb 2006
    Posts
    11,977
    BG Level
    9

    Uh, of course you can't, that's what the constructor is for ;o I'm not going to do the whole solution here, but the above is pretty much the printing code.

  5. #5
    Cerberus
    Join Date
    Apr 2006
    Posts
    498
    BG Level
    4
    FFXI Server
    Fenrir

    Isn't there a way in Java (my familiarity is with that particular flavor of hell known as C#) to convert the value of something entered into its ascii value? And from there, wouldn't you be able to convert the value into binary from the hex... then parse that for the * and " "?

    Edit: nevermind, programming while intoxicated leads to talking paper clips

  6. #6
    netz
    Guest

    Quote Originally Posted by bori View Post
    I'm having trouble implementing the information acquired from the user into the 2d array and then printing it. I have it stored in the 1d array, but I'm not sure how to get it to transfer to the 2d array.
    Transforming to a 2D array is a redundant task.

    Quote Originally Posted by bori View Post
    The thing is it's not always going to be an I. Whatever the user inputs is what is going to be displayed. So I don't think I can have the String input= ".." there. : (
    That's okay, just replace his input string with String that the tester method uses (remove the 2D array stuff first obviously).

    Consider using ArrayList or something to manage the input; take each input (0's and 1's, so a boolean value), test to see if it's valid, and append it to the list, then iterate over your arraylist of booleans and just test true/false to see if you need to print a space or a *, and remember to print a newline every 5.

  7. #7
    Pens win! Pens Win!!! PENS WIN!!!!!
    Join Date
    Jul 2008
    Posts
    8,637
    BG Level
    8

    I actually did so, but the teacher looked at my code and told me just to put a 1d array and not an array list. I had an easier time using an array list though, with all the methods it comes with.

  8. #8
    Black Belt
    Join Date
    Jul 2004
    Posts
    5,720
    BG Level
    8
    FFXI Server
    Bahamut

  9. #9
    Relic Horn
    Join Date
    Mar 2006
    Posts
    3,215
    BG Level
    7

    Quote Originally Posted by bori View Post
    I actually did so, but the teacher looked at my code and told me just to put a 1d array and not an array list. I had an easier time using an array list though, with all the methods it comes with.
    I would assume he's trying to make you get comfortable with using arrays. It's probably more useful to learn that before learning Java classes that imitate arrays.

    You could just use what octopus wrote and put it together with a constructor, and that's most of the functionality you need. I'd have done it more simply than that, but maybe I'm just lazy. Also, he's using strings instead of arrays (even though that's what they really are) and you might get marked down for "not following instructions".

  10. #10
    E. Body
    Join Date
    Jun 2006
    Posts
    2,181
    BG Level
    7
    FFXIV Character
    Bro Teampill
    FFXIV Server
    Gilgamesh
    FFXI Server
    Ifrit

    Here it is in C#. I didn't do it in Java because I didn't want to do all the work for you, but at least this shows how to implement what you want and some test cases. Keep in mind your instructor asked for only 1 instance variable in your class, and you have 2, 4 if you count the static vars as instance variables, although technically a static variable isn't the same as an instance variable, so you should be safe there. It depends on if he meant member variables and made a mistake and said instance variables instead. Better to be safe than get dinged on it though.

    Code:
    using System;
    
    namespace ConsoleApplication
    {
        /// <summary>
        /// Some goofy class to print out zeroes and ones as spaces and asterisks.
        /// </summary>
        class LetterPrinter
        {
            // The single instance variable allowed which caches the string passed in to the constructor.
            private string _Characters = string.Empty;
    
            /// <summary>
            /// Creates an instance of the LetterPrinter class.
            /// </summary>
            /// <param name="Characters">A string containing exactly 35 characters consisting entirely of zeroes and ones.</param>
            public LetterPrinter(string Characters)
            {
                // Check to make sure the string isn't null or empty, and that it contains exactly 35 characters.
                if (string.IsNullOrEmpty(Characters) || Characters.Length != 35)
                {
                    throw new ArgumentException("Class needs to be initialized with 35 \"0\" or \"1\" characters.");
                }
    
                // Validate the data, ensuring that each character in the string is either a zero or a one.
                foreach (char c in Characters)
                {
                    if ('0' != c && '1' != c)
                    {
                        throw new ArgumentOutOfRangeException("Constructor arguments are out of range. Values need to be within the range of 0 or 1.");
                    }
                }
    
                // Store the validated string.
                _Characters = Characters;
            }
    
            /// <summary>
            /// Get accessor to obtains access to the internal _Characters variable. 
            /// </summary>
            public string Characters
            {
                get
                {
                    return _Characters;
                }
            }
    
            /// <summary>
            /// Used to compare two instances of a LetterPrinter class.
            /// </summary>
            /// <param name="lp">An instance of a LetterPriner class to compare to.</param>
            /// <returns>True if the two instances are equal, otherwise False.</returns>
            public bool Equals(LetterPrinter lp)
            {
                if (lp == null)
                {
                    return false;
                }
    
                return string.Equals(this._Characters, lp._Characters);
            }
    
            /// <summary>
            /// Prints the internal character string as a series of spaces or asterisks, in the form of a 5x7 grid.
            /// </summary>
            public void PrintString()
            {
                for (int i = 0; i < _Characters.Length; i++)
                {
                    if ('0' == _Characters[i])
                    {
                        Console.Write(" ");
                    }
                    else
                    {
                        Console.Write("*");
                    }
    
                    if (0 == ((i + 1) % 5))
                    {
                        Console.Write('\n');
                    }
                }
            }    
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                // Some test variables.
                bool CaughtException = false;
                LetterPrinter lp1 = null;
                LetterPrinter lp2 = null;
                string s = string.Empty;
    
                // Initialize a new instance here.
                lp1 = new LetterPrinter("01110001000010000100001000010001110");
    
                // Test out the Get accessor.
                s = lp1.Characters;
    
                // Test out the Equals method, passing in an uninitialized variable first to make sure the two instance do not match.
                if(lp1.Equals(lp2))
                {
                    throw new ArgumentException("lp1 class matches lp2 when lp2 is null.");
                }
    
                // Test the constructor to make sure an exception is thrown when invalid arguments are passed (incorrect length.)
                try
                {
                    lp2 = new LetterPrinter("0101");
                }
                catch (ArgumentException)
                {
                    CaughtException = true;
                }
    
                if (!CaughtException)
                {
                    throw new Exception("Didn't catch ArgumentException when passing invalid args to LetterPrinter class constructor.");
                }
    
                CaughtException = false;
    
                // Test the constructor to make sure an exception is thrown when invalid arguments are passed (invalid characters.)
                try
                {
                    lp2 = new LetterPrinter("342356`sds");
                }
                catch (ArgumentException)
                {
                    CaughtException = true;
                }
    
                if (!CaughtException)
                {
                    throw new Exception("Didn't catch ArgumentException when passing invalid args to LetterPrinter class constructor.");
                }
    
                // Assign the instance variable to an unintialized instance and make sure they match.
                lp2 = lp1;
                if (!lp1.Equals(lp2))
                {
                    throw new ArgumentException("lp1 class does not match lp2 when lp2 should be a match.");
                }
    
                lp2 = new LetterPrinter("01110001000010000100001000010001110");
                if (!lp1.Equals(lp2))
                {
                    throw new ArgumentException("lp1 class does not match lp2 when lp2 should be a match.");
                }
    
                lp1.PrintString();
            }
        }
    }

Similar Threads

  1. Help with Java Programming Project. Get GF off my back plz
    By Azkarin in forum General Discussion
    Replies: 18
    Last Post: 2007-10-10, 10:59