Creating Array Of Objects In Constructor
Mar 16, 2014
I want to create a simple app that takes a name from the console then compares the name to a small phone book,when the name matches another name it will return the associated phone number.
I have a small contacts class which has name and number fields,Then I have a phone book class which populates an array with 4 contact objects that I can compare the entered number against.
here is my contacts class
public class Contact
{
String name;
int number;
[Code].....
In the main method I am just trying to print out one of the fields for one contact to see if I can actually access it to compare it to the name entered.Its saying "MaryJones" cannot be resolved to a type.I'm guessing I cant create all that code in the constructor?
View Replies
ADVERTISEMENT
Jun 13, 2014
Java Code:
class GenericQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void push(E element) {
list.addFirst(element);
}
public E pull() {
return list.removeLast();
[code]...
Is a constructor required to create an object, if one of its instance or class variables haven't been instantiated? Like private String string;
View Replies
View Related
Feb 21, 2015
The experiments will slowly converge towards one big experiment: a simple game. I have just a little interest in games (perhaps I should have more), but making one - even a simple one - should be self rewarding.
However, now to the point.
* The experiment creates an array of rectangle objects.
* The rectangles are painted inside a Frame object at random x,y coords generated by a random number generator
* The rectangles are stationary.
* The rectangles are each assigned their own random colour.
* The array of rectangle objects is created inside the constructor of the class.
The actual code contains various other variables and methods which would distract from a quick analysis, so below is code which has the same logical structure which also fails (instead of array of rectangles, I have used arrays of integers).
import java.util.Random;
/**
* Experiment 14 - see if it works simply - (with integer arrays)
*/
public class TestingArrays {
// instance variables
int N = 10; // the size of the array - 10 elements
int[] a;
[Code]...
View Replies
View Related
Jun 6, 2014
When using Java Code:
Scanner scan = new Scanner(system.in) mh_sh_highlight_all('java');
Why do we put System.in in the constructor? What purpose does it serve and why can't we just not use it?
View Replies
View Related
Mar 22, 2014
import java.util.ArrayList;
public class LectureRoom{
private String courseName;
private String roomNumber;
private String Lecturer;
private ArrayList <Student> studentList;
[Code] .....
Question:
Given the following BlueJ class diagram
Lecturer class (same with previous lab, no changes needed)
Student class (same with previous lab, no changes needed)
LectureRoom (changes occurs here)
1. LectureRoom has roomNumber (e.g. A301), courseName (e.g. Java), lecturer (a reference to a Lecturer object), and studentList (a reference to an ArrayList that stores Student object).
2. LectureRoom has a constructor that receives courseName, roomNumber, and Lecturer. The constructor then sets/assign the courseName, roomNumber and Lecturer. This constructor also creates the studentList arraylist object.
View Replies
View Related
Jul 14, 2014
I thought you can only create a new object using private implementations and then using a constructor to set your arguments inside the parameters of the constructor to the instance variables but how come he created an object without any private implementations and just methods inside the constructor.
import javax.swing.JFrame;
public class MyWindow extends JFrame {
public static void main(String[]args){
new MyWindow();
}
public MyWindow(){
setSize(500,500);
setVisible(true);
setTitle("MyWindow");
}
}
View Replies
View Related
Jan 6, 2015
I have two classes LightController & Circle. I need to use the LightController class to do the following:
Creates an instance of Circle with a diameter of 50 and a colour of OUColour.GREEN and assigns this new circle to the instance variable light.
Sets the xPos of light to 122.
Sets the yPos of light to 162.
I am struggling to write the correct line of code to set the colour to green and set diameter to 50.
Code for the two classes below.
001
import ou.*;
002
import java.util.*;
003
/**
004
* Class LightController
005
* This class uses the Circle class, and the Shapes window
[Code] ......
View Replies
View Related
Sep 18, 2014
Its written that every constructor calls its super class constructor. And we know, constructors are called to create an object. Does it mean that if I am creating an object of a class, I am actually creating objects of all its super class???
View Replies
View Related
Mar 4, 2014
Instructions
Create a WordCounter class with a constructor that takes a file name as a parameter
The class should have two fields: one for the file name and one for a HashMap to store word count information
The constructor should call a private method, countWords, that reads in the file and counts the word frequencies
The class should contain a get method for each field, as well as a print method that prints out the map in the following format:word:frequency
When printing, the map should be sorted by either the word order or frequency (Hint: see Collections.sort)
You should include the sample text file on Blackboard. This is what i got so far
Java Code:
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class WordCounter
[Code] ....
View Replies
View Related
Mar 20, 2014
public class demo
{
Public class static void main(String[]args) {
//Creating a variable that will be a reference to the object
Peoples person_one;
[Code] ....
I have assembled this code below that has a void method which will creat a new object. Problem I encounter is that in
Create_object(person_one);
the person_one has an error saying not initialized. I'm jus trying to learn on my own ways here and practice so may know what's wrong with this? I know I can use a return object from methods but what about this approach?
View Replies
View Related
Dec 30, 2014
I'm trying to create complex Character objects. Each object has a name, and for each object with the same name, they share some of the same initial data. However, there are also some bits of data that are given to the object when it's created. For example, an "Elephant" always starts out having a weight of 500, but its position is determined when it's created. Any of these values may later be changed during runtime.
class CharacterStaticParameters {
int weight;
int numberOfFeet;
int numberOfEyes;
[code]....
For example, whether I should try to use words other than 'static' and 'dynamic', or a nicer word than 'parameters'?
View Replies
View Related
Aug 17, 2014
So I'm still trying to get to grips with Java, and like to understand exactly why I'm doing something, so that I am not just regurgitating the code, If I want to create an object from class "Apples", I would use the following, right?
Apples MyAppleObject = new Apples();
From what I understand, MyAppleObject is the new object name, new -> creates a new instance of it in memory, and Apples() is the onCreate method that is called
So question 1: (just a quick aside question) Can I create an object without calling Apples()? i.e.
Apples MyAppleObject = new;
Question 2: - PARTLY SOLVED - I discovered that (Button) is a way of typecasting, so I understand that line a little better. What I don't understand is why we don't need to initialize the object with "new"
I've now looked at a bit of android development and xml and those declarations are all together different, and I'm not sure why. I haven't found a single explanation for the difference in format.
Java Code:
Button Add;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Add = (Button) findViewById(R.id.button1); mh_sh_highlight_all('java'); So the Button object is declared above the onCreate method, but initialized afterwards I guess....
But instead of using Button Add = new Button() they use Add = (Button) findViewById(R.id.button1);
Question 3:
then In XML they use the following:
Java Code:
public*static*void*main(String[] args){
*********
********// Creates a DOM object in memory. Now you can access
********// data in the xml file
*********
********Document xmlDoc = getDocument("./src/tvshows5.xml"); mh_sh_highlight_all('java');
Once again, why didn't they have to use : Document xmlDoc = new Document()
View Replies
View Related
Sep 14, 2014
I want to make a program where users are prompted to enter a username and a password and have these two values create a new instance of the Object User. But I'm not sure where to start.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
createUser();
[Code] ....
how to take username + password and put it into an object.
View Replies
View Related
Jul 27, 2014
I'm trying to create a simple bar chart from integer values (measuring number of bulldozers) stored in a mySql DB, in the following schema:
Integer rigId PK;
Integer rigQty;
Date recordDate;
String country FK;
I want to plot the date on the x-axis and quantity on y-axis. I can't seem to find any examples of how to render charts from a database. I just find the generic Primefaces 4.0 examples which uses static data like this:
private void createCategoryModel() { // category chart
categoryModel = new CartesianChartModel();
ChartSeries boys = new ChartSeries();
boys.setLabel("Boys");
[Code] ....
I'm really not sure how to adapt the above to a database method nor have any web searches produced useful examples. I tried something like this, but how to find examples or the type of methods I need to use to create a bar graph from Db values:
@ManagedBean(name = "chartb")
@SessionScoped
public class BarChartBean {
private final Map<Integer, Map<String, Number>> rigNums = new HashMap<>();
// private final Map<Integer, Map<String, Number>> HorasOrcadasPorFunci = new HashMap<>();
private CartesianChartModel cartesianChartModel;
[Code] ....
View Replies
View Related
May 25, 2014
I've been trying to write a program for some time now, but im encountering problems while trying to complete it. The program has a student class and a course class (set up with some info about the class, like #, professor name, course title, course time). Now, i have a text file in the workspace, and i have to import the data from the textfile, and thats just what i did, but then there is an option which allows the user to delete a course only by inputing the course number, and when he does that, the program outputs the course's name, and confirms the deletion of the course (From the student's record, i created a vector for that and imported all the courses from the text file). But how can i let the program know what's the name of the course when the user inputs the course number ???
When the data is read from the file, objects should be created and added to the student's course record. <- i think here's where i messed up ? i imported the data, but how can i actually make them objects before adding them into the vector ?
PHP Code:
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
Vector Record = new Vector();
try {FileReader filereader = new FileReader("CLASSES.txt");
BufferedReader bufferedreader = new BufferedReader(filereader);
String test = "";
while(test != null)
{
Record.addElement(test);
test = bufferedreader.readLine();
} mh_sh_highlight_all('php');
View Replies
View Related
Aug 20, 2014
What is the best choice to program like an applet i mean easy with creating multithreading or drawing objects etc.
View Replies
View Related
Feb 7, 2014
I've a parent class with a argument constructor like below(a sample code)
public class Parent {
Parent(String name) {
System.out.println(name);
}
public static void main(String[] args) {
}
}
Also I've child.class which extends Parent.class as shown below,
public class child extends Parent {
child(String name) {
super(name);
}
}
Now, I want create/modify the constructor which is in child, by taking "int i" as an input instead of "String name". How can I do that? Run time I want to execute child constructor not a parent constructor.
Condition is: Without making any changes to the Parent class
View Replies
View Related
Aug 3, 2014
I am working on a problem where i have to create a 2d array with given input of the dimensions (odd number) of array, along with a number within the array and to then print out all of the numbers surrounding that number.
Anyway, i am working on simply making the spiral, which should look like the one below.
n = 3
7 8 9
6 1 2
5 4 3
where the 1 always starts in the center with the 2 going to the right, 3 down, then left etc. etc. I was able to create the code by starting on the outer edges rather than the center and working my way to the middle, however my code always starts from the top left and goes around to the center where it needs to start from the top right. I am having trouble altering my code to meet this criteria. This is what i have thus far.
import java.io.*;
public class Spiral
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of elements : ");
int n=Integer.parseInt(br.readLine());
[Code] .....
View Replies
View Related
Dec 7, 2014
I must fill a 2d array randomly and then apply methods to the array. However i keep getting an out of bounds exception no matter what dimensions i use. I have a test and a class program.
import java.util.*;
import java.lang.Math;
import java.util.Arrays;
import java.util.Random;
class SummerStats {
Random rand = new Random();
[Code] .....
View Replies
View Related
Apr 19, 2014
I am working in NetBeans and I am receiving numerous error messages with my code "not suitable constructor for lineItem.
import java.util.ArrayList;
public class Transaction {
private final ArrayList<LineItem> lineItems;
private int customerID;
private String customerName;
private String LineItem;
private int i;
[Code] .....
Specific Requirements for the Transaction Class :
1. The Transaction class should have a constructor with two parameters. The first is an integer containing the customer's ID and the second is a String containing the customer's name.
2. There should be a method to allow the addition of a line item to the transcript. The three parameters for the addLineItem method will be (1) the item name, (2) the quantity, and (3) the single item price.
3. There should be a method to allow the updating of a line item already in the transaction. Notice that updating an item means changing the quantity or price (or both). The parameters for the updateItem method are also (1) the item name, (2) the quantity, and (3) the single item price.
Notice that the updating of a specific line item requires a search through the ArrayList to find the desired item. Anytime a search is done, the possibility exists that the search will be unsuccessful. It is often difficult to decide what action should be taken when such an "exception" occurs. Since exception handling is not covered until later in this textbook, make some arbitrary decisions for this project. If the item to be updated is not found, take the simplest action possible and do nothing. Do not print an error message to the screen. Simply leave the transaction unchanged.
4. The transaction class needs a method called getTotalPrice to return the total price of the transaction.
5. There should also be a method to return information about a specific line item. It should return a single String object in the same format described for the LineItem class:
Colgate Toothpaste qty 2 @ $2.99 $5.98
Again, the possibility exists that the search for a specific line item will fail. In this instance, you should return a string containing a message similar to this:
Colgate Toothpaste not found.
6. The final method needed is a toString method. It should return the transaction information in a single String object. It should use the following format:
Customer ID : 12345
Customer Name : John Doe
Colgate Toothpaste qty 2 @ $2.99 $5.98
Bounty Paper Towels qty 1 @ $1.49 $1.49
Kleenex Tissue qty 1 @ $2.49 $2.49
Transaction Total $9.96
View Replies
View Related
Feb 11, 2015
So I want to write a constructor that creates a new object with the data from the array values. I don't know where to start. It's the last method in the code:
public class Measurements {
private double[] values;
private double[] newArray;
private int n; //numberofvalues
private double[] ms;
public Measurements(int max) { //constructor
[code]....
View Replies
View Related
Feb 24, 2014
Java Code:
import java.io.*;
import java.util.Scanner;
public class asciiFile {
int height;
int width;
Scanner input;
char[][] poop;
public asciiFile(File f) throws FileNotFoundException{ //constructor
[code]...
The constructor is supposed to take an ASCII file, take the numbers in the file, and populate a 2D array with the numbers in the file.
For some reason, the for loop I use to populate the array works outside of the constructor. When I put it in one of the methods, it runs normally. However, when I keep it in the constructor, I get the following error:
Exception in thread "main" java.lang.NullPointerException
at asciiFile.<init>(asciiFile.java:16)
at main.main(main.java:6)
View Replies
View Related
Mar 12, 2014
I've a vertical-bar-delimited file where most elements contain text, some contain whitespace, and some are empty. Examples:
62RG|fe|Pencil Financial Group, LLC||doug@pencil.com|||85637889|Cross, Ben|bcross@godaddy.net|Bernard|Cross|Ben||315 One Tree Hill Terrace|Lafayette|LA
62RG|fe|Pencil Financial Group, LLC||tracy@pencil.com|||13658734|Dustin Cardwright|dcart@motorola.com|Dustin|Cartwright|||| |LA
which I parse and store with
String str_arry = innline.split( "|", 17);
lisst.add( new Contact( str_arry));
and my Contact class has the constructor
public Contact( String[] str_arry) {
for( int ii = 0 ; ii < str_arry.length ; ii++ ) {
if( str_arry[ii].matches("^s+$")) {
str_arry[ii] = null;
System.out.println("hit a null");
[Code]...
I expect the for-loop in the constructor to find any elements containing whitespace characters and set them to null for subsequent assignment.And when the code runs I do see some hit-statements pop up, so the detecting part is working.
But when I then process the list and access a Contact object and test fields for nulls I don't find any ie
if( aContactObj.getfFCity() == null) System.out.println("city is null");
never prints when it should.
What's the trick? Or is my approach wrong and if so what should it be?
View Replies
View Related
Mar 28, 2014
Exercise the Coin class using a driver class in which 5 coins are flipped, as a group, 1024 times. Display the number of times exactly 4 tails are obtained. Display the number of times exactly 5 tails are obtained. Use an array of Coin.
how to put an object into an array?I know how to make a coin class with a Heads and Tails, but I dont know how to make 5 coins all at once.
View Replies
View Related
Apr 10, 2014
I know the first line below creates an object but the second line creates an array of cars, I'm just not sure how it does that. I can see sportsCar is one object in the array but the others are written in a different way. It seems there should a couple names there instead. Please explain the syntax in this code that's highlighted. I don't know how to make sense of it and I've read through the book where I got it where it explained creating objects.
Auto sportsCar = new Auto("Ferrari", 0, 0.0);
Auto [] cars = {new auto("BMW", 100, 15.0), sportsCar, new Auto()};
View Replies
View Related
Apr 24, 2014
I have a list of objects in my bean (ex: List<Apple> applies = new ArrayList<Apple>() ).The object has several fields (ex: supplier, color, width, height, breadth, etc.)I want to show this list on the front end. However I also want to allow the user to edit the attributes of the apples.So from the front end I will have like a list of fields where a set of fields is related to a single object in the list.I would also like to add/delete apples.
What first came to my mind is to map every field in the object Apple to a List. For example if Apple has field suppliers and field color then in the bean I would create two Lists, List<String> supplier, and List<String> color.From the front end I would display the contents of these Lists rather then the List<Apple> apples.T
he name of the field would be the same for each set of attributes.On save (form submit) the Lists would be re-populated with the field values (changed or not) and then I would be my Apple objects from the bean before saving in database.However I am not sure if there is something in JSF that can achieve this in a simple way, working only with List<Apple> rather than adding additional Lists.
View Replies
View Related