Constructor For Arrays

Apr 23, 2015

I'm wonder about the issue of constructor for arrays. Let say I have a class tablica, and one component int[] tab. If I get it right until now tab is nothing more than empty reference to some unexisting array?

import java.util.Random;
class tablica{
int[] tab;
tablica (){ // i wish it was constructor

[code]....

Then, I'm trying to build the constructor for class tablica. What can be the parameter of such constructor? Is it fields of array? It is simple forf for basic variable

- I liken values defined in constructor with those global defined in class. But how to do it with array component tab.

If I create array object in main method then how can I use this constructor?

View Replies


ADVERTISEMENT

Arrays Classes With Copy Constructor

Sep 29, 2014

Here is the exact instruction for the assignment...

Make 2 classes WrapperShallow and WrapperDeep.
Each class is simply a wrapper class to hold a private array variable. int [] a;
The default constructor for each class should initialize “a”.
Each class should have a toString() and equals().
Each class should have a setArray method that allows you to set the “a” variable.
WrapperShallow should have an invalid copy constructor.

[Code] ,....

Think about why shallow is wrong and deep is correct! What happens to the old “a” in the WrapperDeep copy
constructor? (think garbage collection)

Example Output:

--------------------Configuration: <Default>--------------------
**** TESTING SHALLOW OBJECTS ****
inital shallow object contains
7 17 77
copy shallow object contains
7 17 77
inital shallow object changed to
13 14 15
copy shallow object not changed contains
13 14 15

[Code] .....

So far I've only finished part of the WrapperDeep class. I can't get my equals method to work properly, I keep getting the error:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
at WrapperDeep.equals(WrapperDeep.java:27)
at WrapperTest.main(WrapperTest.java:18)
Java Result: 1

My class looks like this:

public class WrapperDeep {
private int a[] = new int[3];
public WrapperDeep(int x, int y, int z){ //constructor initializes 3 integers in array
a[0] = x;
a[1] = y;
a[2] = z;

[Code] ....

View Replies View Related

What Is The Difference Between Regular Arrays And Multi Dimensional Arrays

Jun 28, 2014

I mainly would like to know is a int[4][4] or a int [4*4] is more efficient to use. Which takes more storage? Which requires more to process? that kind of stuff.

View Replies View Related

Non-Parameter Constructor Calls Two Parameter Constructor

Apr 19, 2014

I was practicing my java skills and came across an exercise in which a non parameter constructor calls a two parameter constructor. I tried a few searches online but they all came back unsuccessful. This is the part I am working on:

public PairOfDice(int val1, int val2) {
// Constructor. Creates a pair of dice that
// are initially showing the values val1 and val2.
die1 = val1; // Assign specified values
die2 = val2; // to the instance variables.
}
public PairOfDice() {
// Constructor that calls two parameter constructor
}

I tried calling the two constructor using the line "this(val1, val2)" but I get an error because val1 and val2 are local variables.

Then I tried to use the same signature: "this(int val1, int val2)" but that didn't work either.

View Replies View Related

Constructor With Parameters

Jan 31, 2015

public class TestClass {
public TestClass(String k){System.out.println(k);}
public static void main(String[] args) {
try {
hello();
}
catch(Exception e){System.out.println(e);}

[Code] ....

Explain how to catch block act as constructor with parameter?

View Replies View Related

Cannot Set Ints From Constructor

Aug 10, 2014

Java Code:

package ZooZ;

import java.util.Random;
public class Animal {
int playerOne; <------- Remains 0
int playerTwo; <------- Remains 0
Random random = new Random();

[Code] ....

If you look at the code, I set "playerOne" and "playerTwo", to set them as what was passed in from another class..

In the Animal constructor.

in that constructor the value is 2. But when I use it in the "Bash()" method it is 0 in the console.

Why doesnt the playerOne and playerTwo stay the value it is assigned in the constructor.??

View Replies View Related

Why Constructor Cannot Be Final

Oct 27, 2014

"A constructor cannot be abstract, static, final, native, or synchronized."

I understand on why it can't be all of the above, except "final".

Why can't we have a final constructor, i understand constructors are not inherited, hence no chance/case of overriding etc. But why is it not allowed at all ?

View Replies View Related

No Such Constructor Error

Oct 27, 2014

So I am working on a school project and I have 2 classes, class FakeGravity contains all the properites and class BouncyBall is my driver class. For some reason when I try writing

FakeGravity gravity = new FakeGravity( );

I get an error. I am attaching an image of the error, and also attaching the program just in case you need more information. Also I was using blueJ to write the program

dcasarrubias, on 27 October 2014 - 02:44 PM, said:

So I am working on a school project and I have 2 classes, class FakeGravity contains all the properites and class BouncyBall is my driver class. For some reason when I try writing

FakeGravity gravity = new FakeGravity( );

I get an error. I am attaching an image of the error, and also attaching the program just in case you need more information.

View Replies View Related

No Default Constructor

Nov 2, 2014

The LocalStudent class inherits the Student class. The IDE states an error of "no default constructor in Student class".I understand that if a LocalStudent object is created, the default constructor of its superclass (aka Student class) will be called implicitly.there is no LocalStudent object being created, so why is the default constructor of Student being called ?

The default constructor of LocalStudent is also overloaded by the created no-arg constructor containining subjects = null; . So there is no call to the superclass default constructor from the default constructor of LocalStudent.

public class Student {
private char year1;
public Student(String name, char year){
year1 = year;
}
public char getYear(){
return year1;

[code]...

View Replies View Related

Radius Value Becoming Zero In Constructor

Jul 8, 2015

I am trying to create a user defined Exception. I am using a hard-coded value in the constructor of circle class at the time of object creation.But in the constructor this value becomes 0.

import java.lang.Exception;
import javax.swing.*;
class InvalidRadiusException extends Exception{
private double r;
public InvalidRadiusException(double radius){
r = radius;

[Code] ....
 
Due to this its always generating InvalidRadiusException even if i am supplying a non-zero non-negative value.

View Replies View Related

Adding Validation To A Constructor?

Nov 17, 2014

I want to add validation to some of the elements in my constructor.

Person(String idIn, String nameIn, ) {
this.id = idIn;
this.name = nameIn;
}

I want to be able to check that the data for the ID is limited to a certain collection of characters formatted in a certain. For example, I may wish to limit it to 5 lowercase letters or numbers, or a combination of both. How could I do this?

View Replies View Related

Constructor In Abstract Class?

Jun 23, 2014

Do we have constructor in abstract class? If we have then what is the use of it?

View Replies View Related

Overloaded Constructor Not Being Implemented?

Oct 21, 2014

For some reason, even though I am giving it the correct number of arguments for the constructor to be initalized it doesn't go through. I end up with a compile error:

PatientBuilder.java:17: error:

constructor Patient in class Patient cannot be applied to given types;
Patient aPatient = new Patient(bloodType, rhFactor, ID, age);
^
required: no arguments
found: String,String,int,int
reason: actual and formal argument lists differ in length

And I'm not understanding how that's possible when it calls for 2 strings and 2 ints and that's what I am passing.

I have this in my main method Scanner inputDevice = new Scanner(System.in);

System.out.println("What is the patients ID number?");
int ID = inputDevice.nextInt();
System.out.println("What is the patients age?");
int age = inputDevice.nextInt();

[Code] ....

And then here are my two constructors, one default and one overloaded.

public Patient() {
patientBlood = new BloodData();
ID = 0;
age = 0;
bloodType = "O";
rhFactor = "+";

[Code] .....

View Replies View Related

Stuck On Constructor With Parameters

Mar 19, 2014

How to use a constructor with parameters where the user inputs the information? I'm doing a problem where I create a Delivery class that accepts arguments for the year, delivery number within the year, distance code (1 for short distance, 2 for long), and weight of package. The constructor is supposed to also determine the eight digit delivery number (combining the year and delivery number, like 20140054 for this year, package #54).

I know I'm not close to being done but I'm struck on the application with the constructor parameters. If I'm asking the user to input the information, does that mean I have to create a no argument constructor so it will compile? Right now it won't compile because it's asking for the parameters but I can't put them.

This is the class:

public class Delivery {
int year;
int delNum;
double weight;
int code;

[Code] .....

And the error is:

CreateDelivery.java:22: error: constructor Delivery in class Delivery cannot be applied to given types;
Delivery firstDelivery = new Delivery();
^
required: int,int,int,double
found: no arguments
reason: actual and formal argument lists differ in length
1 error

View Replies View Related

Returning Data From A Constructor?

Sep 1, 2014

I'm having an issue returning data from a constructor. This is an assignment, and the specifications were that two classes are to be used, one for the variables and assigning methods, and one for the main method and the printing. This app compiles, but returns "0" for the isbn number, and I'm sure it's because I'm not doing something right with my constructors. My code is below

public class Book {
/* Declare Variables */
public static int isbn;
/* Constructor */
public Book (int isbn) {
isbn = 454545;

[code]....

There are other variables to add, but if I can get one working, I can get the rest working.

View Replies View Related

Sending Two Strings Into A Constructor

Jun 13, 2014

I did this using ArrayList<String> and my tests worked. Meaning I was able to read the strings in a different class through my constructor. However I want to use a string array because it will be easier to handle when I finish the program. I will send each players poker hand in and figure out who is the winner instead of putting it all onto a ArrayList and having to iterate through it. However whenever I did my check I am just printing null.

PokerFile class

void separateHands(String cards) {
//ArrayList<String>playerOne = new ArrayList<String>();
//ArrayList<String>playerTwo = new ArrayList<String>();
String[] playerOne = new String[10];
String[] playerTwo = new String[10];
 
[Code] .....

ignore the boolean methods I was just building the structure of the program. The print file is what is outputting this:

null
null
null
null
null
null

public class WinningHand extends PokerFile {
//ArrayList<String> p1 = new ArrayList<String>();
//ArrayList<String> p2 = new ArrayList<String>();
String[] p1 = new String[6];
String[] p2 = new String[6];
WinningHand(String[] p1,String[] p2)

[Code] ....

View Replies View Related

How To Scan Input And Use It In A Constructor

Oct 2, 2014

what weapon the user wants to use and set the element of the Player but I can't use defineWeapon() inside of the constructor so what can I do?here's the player class (where I need to set the element which is the second string in the constructor

package netHackDessart;
import java.util.Scanner;
public class Player extends Monster {
public Player()
{
super("player", "null", 18, 6, 150, 4, 1, 6, 1, 8, 1, true, false);

[code]....

View Replies View Related

Return Statement In A Constructor

Jan 8, 2014

What is the difference between two statements:

Class1 class1 = new Class();
class1 = Class2.method1();

and

Class1 class1 = Class2.method1();

I have one more query on the same lines ... I always need to call the method1 of Class2 whenever i create a object of class1. So I wanted to go with the constructor in Class1. But the method1 in Class2 has a return statement. so is there any better way to do this other than constructors.

Sample code:

public int class Class2{
public static method1(){
return 2;
}
}
public class Class1{
public Class1(){
Class2.method1();
}
}

View Replies View Related

How To Get A Variable From Constructor Into Another Method

Nov 11, 2014

I am having an issue with a small part of my project. i am supposed to make a hash table with a file containing words. The file is being passed into my constructor, where i basically just all it "filename" of type string. Im supposed to get the contents of the file and put it into the table. the problem I'm having is making the connection between my constructor and a method called "start" which basically does all the work. Im not sure how to go by doing this, how could i use the variable "filename" from my constructer in my start method?:

import java.io.*;
import java.util.*;
public class WordCount {
//private fields, including your HashMap variable
HashMap<String,Object> hmap =new HashMap<String,Object>();//(table size,load factor)
public WordCount( String infileName){
String filename =infileName;

[Code] .....

View Replies View Related

How To Make A Constructor Visible

Jul 10, 2014

Constructors are public by default ,aren't they?

import java.awt.Frame;
import java.awt.SplashScreen;
import javax.swing.JOptionPane;

[Code]....

This code gives me error

The constructor SplashScreen(long) is not visible

View Replies View Related

Can Call One Constructor From Two Different Constructors?

Nov 19, 2014

I am getting error in second constructor that I have created, it gives an error: cannot find symbol variable

package Objects;

import javax.swing.JOptionPane;
public class Constructor {
public static void main(String[] args) {
Piggybank1 pg1 = new Piggybank1("Abhinav", 500);
pg1.deposit(200);
pg1.withdraw(10);

[Code] ....

View Replies View Related

Timer Constructor Is Not Defined

Feb 13, 2014

In my main method I am trying to create a Timer, but when I put new Timer(1000,listener) the constructor is not defined. It is when there is nothing in it. I find this super weird because in all my other programs this does not happen. I looked at the documentation and can't see what I am doing wrong, so I turn here.

ActionClass Java Code: import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Action extends JComponent {

[Code] .....

View Replies View Related

Empty Constructor - Using OOP In Java

Feb 8, 2014

I have 2 classes:

1) productType that have name and price of the productType and an empty consturcor.
2) superMarket that have name of supermarket and arraylist of productTypes (

private ArrayList<ProductType> products;

) and an empty constructor.

In each class I have function that get input from console and should store it into each class variables.

In productType i have function:

public void getFromUser() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter product name:");
name = br.readLine();
System.out.println("Enter price:");
price = Integer.parseInt(br.readLine());

[Code] ....

The main is something like:

public static void main(String[] args) throws IOException{
SuperMarket s1 = new SuperMarket();
SuperMarket s2 = new SuperMarket();
 s1.getFromUser();
}

The problem is when i get to line "products.add(i,p)" I get java.lang.NullPointerException

In the debug mode I can see that when I get to this line the "products" is null.

why do you think this happening, when I do "new SuperMarker()" in the main it should run the empty constructor and create new arraylist...

View Replies View Related

How To Pass Filename Into Constructor

Feb 26, 2015

I'm taking inheritance now and some things look confusing. I'm trying to do the following but the code, in particular, the constructor in subclasses are pointed to be wrong. The constructor in LongestWord is not correct,how to pass the filename into the constructor?

Java Code:

import java.util.Scanner;
import java.io.File;
public abstract class FileProcessor {
protected Scanner input;
public FileProcessor(String filename) throws Exception

[Code] ....

View Replies View Related

Why Put Other Objects In Object Constructor

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

ArrayList In No Arguments Constructor

Sep 29, 2014

I have been able to create a no arg constructor and pass empty double, int, and strings but i am not able to pass an arraylist.

class Savings {
private double balance;
private ArrayList <String> transaction = new ArrayList();
public Savings (double B)/>
{
balance = b;
}
public Savings()
{
this(0.0,new ArrayList());
}

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved