Solved

Help with programming project

Posted on 2008-06-15
9
844 Views
Last Modified: 2011-10-19
I am writing a project for school and am at an impasse. I can't seem to get the data from my input file into my array. My values seem to be returning the default values only.

The problem is as follows

# Write a class Name that stores a person's first, middle, and last names and provides the following methods:

    * public Name(String first, String middle, String last) -- constructor. The name should be stored in the case given; don't convert to all upper or lower case.
    * public String getFirst() -- returns the first name
    * public String getMiddle() -- returns the middle name
    * public String getLast() -- returns the last name
    * public String firstMiddleLast() -- returns a string containing the person's full name in order, e.g., "Mary Jane Smith".
    * public String lastFirstMiddle() -- returns a string containing the person's full name with the last name first followed by a comma, e.g., "Smith, Mary Jane".
    * public String initials() -- returns the person's initials (a 3-character string). The initials should be all in upper case, regardless of what case the name was entered in. (Hint: Instead of using charAt, use the substring method of String to get a string containing only the first letter -- then you can upcase this one-letter string. See  in the text for a description of the substring method.)

 
# Now write a program TestNames.java that reads in ten names from an input file (you'll need first, middle, and last for each), creates a Name object for each, and uses the methods of the Name class to do the following:

    * displays the person's full name and initials on the screen(a 3-character string). The initials should be all in upper case, regardless of what case the name was entered.  For example:

      Mary Jane Smith MJS
      john donald doe JDD

       
    * writes the last-first-middle version (e.g., "Smith, Mary Jane"  )of each name in the input file to an output file.


I am not too concerned about the writing to a file yet. I can figure that out I think. My biggest problem is trying to find out why my input does not go into the array (or if it is why I can't access it)

public class Name

   {

      private String first;//First name

      private String middle;//Middle name

      private String last;//Last name

      private String initials;//Three character initials                   

    // ------------------------------------------------------------

   //   Default constructor - to initialize the variables

   // ------------------------------------------------------------

       Name(){

         first = "Tom";

         middle = "Jim";

         last = "Bob";             

         initials = "jjb";

      }

      private String newFirst , newMiddle, newLast ; // Name parts

   

   // ------------------------------------------------------------

   // Another constructor - with three parameters - if you know the first and middle and last name

   // ------------------------------------------------------------

       Name(String first, String middle, String last){

         first = newFirst;

         middle = newMiddle;

         last = newLast;   

      }

   

     

   

   // ------------------------------------------------------------

   //   Accessor methods

   // ------------------------------------------------------------

   

       public String getFirst(){

         return first;

      }

       public String getMiddle(){

         return middle;

      } 

       public String getLast(){

         return last;

      }

         

   

   // ------------------------------------------------------------

   //   Mutator methods

   // ------------------------------------------------------------

       public void setFirst(String newFirst){

         first = newFirst;

      }

       public void setMiddle(String newMiddle){

         middle = newMiddle;

      }

   

       public void setLast(String newLast){

         last = newLast;

      }

       public String firstMiddleLast(){

         return first + " " + middle + " " + last;

      }

   

   

   // ---------------------------------------------------------

   // Return the Initials

   // ---------------------------------------------------------

       public String initials(){

         return first.substring(0,1).toUpperCase()+

            middle.substring(0,1).toUpperCase()+

            last.substring(0,1).toUpperCase();

      

                  

                        

      }

   

   

        

   }// End Class

 

 

import java.util.Arrays;                

 

    public class TestName{

    

    

       

   

     // ---------------------------------------------------------

       public static void main(String[] args) throws Exception {

      // Create a File instance

         java.io.File file = new java.io.File("names.txt");

       

        // Name[]nameArray;

        

       //  nameArray = createNameArray();

         

        //Print Name Array

       //  printNameArray(nameArray);

                 

      // Create a Scanner for the file

         java.util.Scanner input = new java.util.Scanner(file);

      

      // Read data from a file

         while (input.hasNext()) {

            String first = input.next();

            String middle = input.next();

            String last = input.next();

                

            Name[]nameArray;

         

            nameArray = createNameArray();

            printNameArray(nameArray);

          //System.out.println(first + " " + middle + " " + last + " " + "nameArray[i].initials()");

         }

        

      // Close the file

         input.close();

      }

         

        

      public static Name[] createNameArray() {

         Name[]nameArray = new Name[10];//create an object

         int j = 0;

         for (int i = 0; i < nameArray.length; i++, j++) {

            nameArray[j] = new Name();

         }

         return nameArray; //Return Name Array

         

        

      }

    

       public static void printNameArray

       (Name[] nameArray){

         int j = 0;

         for (int i = 0; i < nameArray.length; i++, j++) {

         

           //nameArray = java.util.Arrays.toString(nameArray[j]);

            System.out.println(nameArray[j] + nameArray[j].initials());

           //  System.out.println(java.util.Arrays.toString(nameArray[j]));

         }

         

      }

   }

Open in new window

names.txt
0
Comment
Question by:Hueydude
9 Comments
 
LVL 3

Expert Comment

by:ineya
Comment Utility
1. You should not create nameArray inside while loop
2. after you read one name from file you should create Name object store it in nameArray an corresponding index -> you need some counter variable in while loop
0
 
LVL 2

Expert Comment

by:Airyck666
Comment Utility
You can't create your array within the loop.  And since the length of the array in unknown, a Vector would be better.  Here I have rewritten  the main method and a new method called printNameVector().
No more need for the createArray method.  Remeber that when readong the Name objects from the Vector they will have to be cast to Name.  I.E.
Name nameObject = (Name)nameVector.get(index);

Let me know if you don't understand
public static void main(String[] args) throws Exception {

    // Create a File instance

    java.io.File file = new java.io.File("names.txt");
 

    java.util.Scanner input = new java.util.Scanner(file);
 

    java.util.Vector nameVector;
 

      // Read data from a file

    while (input.hasNext()) {

        String first = input.next();

        String middle = input.next();

        String last = input.next();
 

        Name name = new Name(first, middle, last);
 

        nameVector.add(name);

    }
 

    printNameVector(nameVector);
 

    // Close the file

    input.close();

}
 

    

public static void printNameVector(Name[] nameVector) {

    Name name;

    String first;

    String middle;

    String last;

    for (int i = 0; i < nameVector.size; i++) {

        name = (Name)nameVector.get(i);

        first = name.getFirst();

        middle = name.getMiddle();

        last = name.getLast();
 

        System.out.println(first + " " + middle + "  " + last + "\n");

    }

}

Open in new window

0
 
LVL 2

Expert Comment

by:Airyck666
Comment Utility
oh... and this is in the wrong zone... that's not javascript :)
0
 

Author Comment

by:Hueydude
Comment Utility
Thanks for the response. I had the "create Array" outside the loop but it wasn't doing any better. The whole vector thing is beyond my level. I appreciate it but it's too advanced for what I am doing. I need to keep this at the array level. The length of the Array would be 10 as there are ten names in the input text.

Even when I had the Create Array outside the loop I couldn't seem to get the information into the array.
The create arrays are in the original file but commented out. Putting it back just gives me the same result

Name@3e25a5 hi TJB
Name@19821f hi TJB
Name@addbf1 hi TJB
Name@42e816 hi TJB
Name@9304b1 hi TJB
Name@190d11 hi TJB
Name@a90653 hi TJB
Name@de6ced hi TJB
Name@c17164 hi TJB
Name@1fb8ee3 hi TJB

This looks like it points to the location, not the name and the initials are from the constructor. I put the "hi" in there just to ensure I knew what was printing.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 29

Expert Comment

by:Badotz
Comment Utility
>>I need to keep this at the array level

Because that is the homework requirement, eh?
0
 
LVL 2

Expert Comment

by:Airyck666
Comment Utility
Ok... fair enough.  I rewrote it using arrays


public static void main(String[] args) throws Exception {

    // Create a File instance

    java.io.File file = new java.io.File("names.txt");
 

    java.util.Scanner input = new java.util.Scanner(file);
 

    Name[] nameArray = new nameArray[10];
 

      // Read data from a file

    int index = 0;

    while (input.hasNext()) {

        String first = input.next();

        String middle = input.next();

        String last = input.next();
 

        Name name = new Name(first, middle, last);
 

        nameArray[index++] = name;

    }
 

    printNameArray(nameArray);
 

    // Close the file

    input.close();

}
 

    

public static void printNameArray(Name[] nameArray) {

    Name name;

    String first;

    String middle;

    String last;

    for (int i = 0; i < nameArray.length; i++) {

        name = nameArray[i];

        first = name.getFirst();

        middle = name.getMiddle();

        last = name.getLast();
 

        System.out.println(last + ", " + first + "  " + middle + "\n");

    }

}

Open in new window

0
 

Author Comment

by:Hueydude
Comment Utility
Thanks for the help. I am getting closer but no cigar.
I am getting an error on the following line
 Name[] nameArray = new nameArray[10];   ----  (TestName.java:23: cannot find symbol on "nameArrayl")

I changed it to Name[] nameArray = new Name[10]; and it would compile but the output was all null. I couldn't get it to change to anything else (that I could think of) that would compile.
0
 
LVL 2

Accepted Solution

by:
Airyck666 earned 250 total points
Comment Utility
that problem is in your constructor.  Here's the whole thing rewritten.  
public class Name {

	private String first;// First name
 

	private String middle;// Middle name
 

	private String last;// Last name
 

	private String initials;// Three character initials
 

	// ------------------------------------------------------------

	// Default constructor - to initialize the variables

	// ------------------------------------------------------------

	Name() {

		first = "Tom";

		middle = "Jim";

		last = "Bob";

		initials = "jjb";

	}
 

	// what are these for?

	//private String newFirst, newMiddle, newLast; // Name parts
 

	// ------------------------------------------------------------

	// Another constructor - with three parameters - if you know the first and

	// middle and last name

	// ------------------------------------------------------------

	Name(String first, String middle, String last) {

		/*

		 * This constructor was not assigning the classes properties

		 */

		this.first = first;

		this.middle = middle;

		this.last = last;

	}
 

	// ------------------------------------------------------------

	// Accessor methods

	// ------------------------------------------------------------
 

	public String getFirst() {

		return first;

	}
 

	public String getMiddle() {

		return middle;

	}
 

	public String getLast() {

		return last;

	}
 

	// ------------------------------------------------------------

	// Mutator methods

	// ------------------------------------------------------------

	public void setFirst(String newFirst) {

		first = newFirst;

	}
 

	public void setMiddle(String newMiddle) {

		middle = newMiddle;

	}
 

	public void setLast(String newLast) {

		last = newLast;

	}
 

	public String firstMiddleLast() {

		return first + " " + middle + " " + last;

	}
 

	// ---------------------------------------------------------

	// Return the Initials

	// ---------------------------------------------------------

	public String initials() {

		return first.substring(0, 1).toUpperCase()

				+ middle.substring(0, 1).toUpperCase()

				+ last.substring(0, 1).toUpperCase();
 

	}
 

}// End Class
 
 
 
 

public class TestName {
 

	public static void main(String[] args) throws Exception {

		// Create a File instance

		java.io.File file = new java.io.File("names.txt");
 

		java.util.Scanner input = new java.util.Scanner(file);
 

		Name[] nameArray = new Name[10];

		

		System.out.println(input.delimiter());
 

		// Read data from a file

		int index = 0;

		while (input.hasNext()) {

			String first = input.next();

			String middle = input.next();

			String last = input.next();
 

			Name name = new Name(first, middle, last);
 

			nameArray[index++] = name;

		}
 

		printNameArray(nameArray);
 

		// Close the file

		input.close();

	}
 

	public static void printNameArray(Name[] nameArray) {

		Name name;

		String first;

		String middle;

		String last;

		for (int i = 0; i < nameArray.length; i++) {

			name = nameArray[i];

			first = name.getFirst();

			middle = name.getMiddle();

			last = name.getLast();
 

			System.out.println(last + ", " + first + "  " + middle + "\n");

		}

	}

}

Open in new window

0
 

Author Closing Comment

by:Hueydude
Comment Utility
Thanks very much. I appreciate the help. I am still learning here and while I have some work to do to finish this project you have set me back on course. Thanks again!!!
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Auto Submit on dropdown box 19 34
Python On Mouseover Save URL/Link 4 29
Accessing data in JSON response.d 4 27
angularls and plnkr 14 17
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now