Constructor That Creates A New Object With Data From Array Values?

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


ADVERTISEMENT

Creates Two Die Objects And Roll Them Display The Values

May 4, 2014

I've written a die program, and i want the user to type any key in order to continue, how do i achieve this ?

I have already created a Die class, i just want to implement the main method now.

PHP Code:

package test;

/* This program demonstrates the use of a user-defined class

public class RollingDice {
// Creates two Die objects and rolls them display the values.
public static void main (String[] args) {
Die die1 = new Die();
System.out.println("Roll the die ")
}
} mh_sh_highlight_all('php');

What should i add after System.out.println, So that the user types (any key, or types "Enter" for example, for the die to roll). i dont want the die to roll by itself i Want the user to interact with the program in order for it to roll.

View Replies View Related

Working On A Program That Creates Array From A File

Feb 19, 2015

Working on a program that creates an array from a file, organizes it in various ways, and then prints the results. Right now I'm specifically having trouble with the printAry() method - when I try to run it, I receive a NullPointerException for the active line in printAry() (EDIT: line 102). Not sure which sections are important to this, so I will include the client class and most of the service. I realize that the amount of documentation I included is not necessary, but it is required for the class.

class Lab3StudentAryService
{
private int count;
private Lab3StudentData [] studentAry = new Lab3StudentData[50];

/*
@param: none
@return: none
reads file and converts to array.
*/
public void fillAry() //constructor
{
Scanner scan = new Scanner(System.in);

[code]....

View Replies View Related

Declare And Creates Integer Array That Can Hold 15 Integers

Nov 3, 2014

The main Method

-Create a main method declares and creates an integer array called nums that can hold 15 integers.

-Use a for loop to fill that array with multiples of 3: 0, 3, 6, 9, etc.

-Then use similar for loop to print each value in the array on one line, with each value separated by a single space.

-Compile and run the program to see the result:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

As you write other methods, you'll also modify the main method to make calls to them. The printArray MethodWrite a method called printArray that accepts an integer array as a parameter. This method does not return a value, and must be declared as static so that the main method can call it. Instead of printing the array in the main method, move that loop into this method. Call the printArray method from the main method. Compile and run the program to verify it prints the sam result as before.Add a println statement so that after printing the array values on one line, it then moves to the following line.Finally, modify the loop in the printArray method so that, instead of using a traditional for loop, it instead uses a for-each loop. Compile and run the program again.

Part III: More Array Methods

The linearSearch Method In lecture we looked at a method that performed a binary search on a sorted array. A much simpler (though much less efficient) search is a linear search, that simply starts at the front of the array and looks at each element in turn until it finds it or reaches the end.Create a method called linearSearch that accepts an integer array and a single int value as parameters. The goal of the method is to find the second parameter (the target) in the array. The method should return a single int representing the index of the target value. This method should not print any output itself. In this method, use a traditional for loop to scan through the elements in the array. As soon as you find the target value, return the index of that value.

If you scan through the entire array without finding the target value, return a -1.Modify the main method to call the linearSearch method and print the results. Call it twice, searching for the value 18 (which it should find) and the value 10 (which it should not). Including the previous activity, the output of the main method should now look similar to this:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

The index of 18 is 6

The index of 10 is -1

The sumArray Method

The sumArray method should take an integer array as a parameter and return a single integer representing the sum of all values in that array.Use a for-each loop to access each value in the array and compute a running sum. After the loop, return the total.Call the method from the main method, producing the following augmented output:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

The index of 18 is 6

The index of 10 is -1

The sum of this array is 315

The addValue Method...The addValue method should accept an integer array and a single int as parameters. The purpose of the method is to add the second parameter to EACH value in the array. The addValue method does not return a value, but the elements inside the array will be modified. Call the addValue method from the main method, adding 100 to each element in the array. Then call the printArray method again to see the modified array values:0 3 6 9 12 15 18 21 24 27 30 33 36 39 42

The index of 18 is 6

The index of 10 is -1

The sum of this array is 315 100 103 106 109 112 115 118 121 124 127 130 133 136 139 142

Test a Different Array..Finally, duplicate the content of the main method to perform similar tests on another array. Instead of filling it with multiples of 3, fill it with multiples of 4. And instead of using an array size of 15, use an array size of 20.Modify the values search for to include one that is in the array and one that isn't.Rerun the main method and carefully check the results.If you haven't been doing it all along (which you should), make sure the appropriate class and method documentation is included.When you're satisfied that all methods are working correctly, modify the main method to delete the second array tests.

View Replies View Related

Creates Array Of 3 Consecutive Ints (0 - 7) User Has To Guess What Those Numbers Are

Aug 16, 2014

I have the following program. In a nutshell, I creates an array of 3 consecutive ints and the user has to guess what those numbers are, knowing that they are between 0 and 7, this is from Head First Java. In the book, the code has a bug that is made on purpose and they challenge you to fix it. As you can see bellow, every time a user's guess matches a int in the array, the NumOfHits is increased by one. When the NumOfHits is 3 (the length of the array) the game finishes.

The bug is that if you guess 1 and 1 is in the array, if you type in 1, 3 times, I will increase the NumOfHits 3 times and end the game as if you had won. To solve the bug, you need to find a way to tell the program that if the user already guessed that number, it should no longer be taken into account and we shouldn't increase the NumOfHits if the same number is provided.

I "fixed" this by searching for the index of the number that matches an int of the array, and changing that index's value to 100, since the user knows that the numbers are between 0 and 7, they will not submit 100.

The result? If the user submits 2 and 2 is in the array, the value of its indexed is replaced by 100, so that if the user submits 2 again it doesn't count as a match.

Please see the comments in the code

import java.io.*;
import java.util.Arrays;

class DotCom{
int NumOfHits = 0;
int[] LocationCells;
public void setLocationCells(int[] locs){
LocationCells = locs;

[Code] .....

The code works, but for some reason, some times I get a ArrayIndexOutOfBoundsException run time error and it appears to be somehow random. This is what I saw on the command line earlier

C:Userspablo.alvarez>java launchDotCom

Enter a number: 3
missed
Enter a number: 4
hit
Enter a number: 5
hit
Enter a number: 7
missed
Enter a number: 5
missed
Enter a number: 4
missed
Enter a number: 3
missed
Enter a number: 4
missed
Enter a number: 5
missed
Enter a number: 6

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at DotCom.checkYourSelf(launchDotCom.java:16)
at DotComGame.startGame(launchDotCom.java:59)
at launchDotCom.main(launchDotCom.java:72)

As you can see here, 3 returned 'missed' but 4 and 5 returned hit. Since the numbers are in sequence and are only 3, it makes sense that the last number is 6 (4,5,6). You will then notice that when I submitted 3 and 4 again it returned 'missed' as expected, because the numbers were already matched earlier, but then when I submitted 6, it returned the error seen above.

Sometimes this doesn't happen at all, sometimes it happens at the 2nd guess or third, it appears to be somehow random. I'm familiar with the error message, but I don't see where I'm using an index that doesn't exist in the array. The only time I'm referencing an array index is on

LocationCells[index] = 100;

but the index variable will only hold a value if the int submitted by the user matches on of the values in one of the indexes, so how is it that I'm going over the number of available indexes?

View Replies View Related

How To Display Default Constructor Values

Sep 13, 2014

I am writing a program that accepts input from the user, I want default values displayed before the input values.

Java Code:

public surfboards() {
surfboardType = "Type not assigned";
shaperName = "Shaper not assigned";
constructionType = "Construction Type not assigned";
surboardSize = 0D;
} mh_sh_highlight_all('java');

I can get the output to display as shown below

(THIS IS WHERE I WANT DEFAULT CONSTRUCTOR DISPLAYED. Currently not displayed)

Type not assigned
Shaper not assigned
Construction Type not assigned
0 Feet

(THIS IS WHERE I WANT DEFAULT CONSTRUCTOR DISPLAYED. Currently not displayed)

input:

Java Code:
Enter Surboard Type:
test
Enter Shaper Name:
test
Enter Surfboard Construction Medium:
test
Enter Surfboard Size:
6.5 mh_sh_highlight_all('java');

Output:
test
test
test
6.5 feet

View Replies View Related

Calling Out Constructor And Assigning Values To It From A Scanner

Oct 16, 2014

import java.util.Scanner;
public class Try{
static String name;
static int age;
static Scanner a = new Scanner(System.in);
static Scanner b = new Scanner(System.in);
static Scanner c = new Scanner(System.in);
public Try(String name, int age){

[Code] ....

I was trying to make a program that asks the user to create a person or a group of persons and assign names and age to them. So I made a constractor "Try" and a method "AskUser".in AskUser() I use a do/while loop where user is asked to input a name, an age and if he likes to create another person. Now how do I take the input data each time the loop runs, and send it to constractor to create new objects with it? And how these new objects will be called?

View Replies View Related

Assigning Private Variables Values From Constructor

Jun 13, 2014

I am able to get output from my constructor when I place a loop inside of it. However when I try to access the private variable that I thought was set by the constructor I get nothing. When I check its size it is zero as well.

Java Code:

public class WinningHand extends PokerCalculator {
private int p1Size;
private int p2Size;
private String[] p1Hand = new String[p1Size];
private String[] p2Hand = new String[p2Size];

[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

Tracking Constructor To See If It Recreate Object

Aug 2, 2014

that i started to learn programming and i started with java. so there is a book that i'm on it right now called "Pearson Absolute Java 5th Edition" by Walter Savitch anyway i'm on a project in fifth season which i have to create a class named HotDogStand that operates several hotdog stands distributed throughout town. the whole program is clear. although its so easy to accomplish , my question is more about debugging. so here is the code:

public class HotDogStand
{
private int id; //id number of hotdog stand
private int hotDogsPerDay; //hotdogs sold by one stand
private static int totalHotDogs; //the static value for total hotdogs sold by all the stands
public HotDogStand (int newID, int hotDogsPerDay) {
this.id = newID;
this.hotDogsPerDay = hotDogsPerDay;
totalHotDogs += hotDogsPerDay; //to add the value every time the user uses the constructor (every time the user creates an object)

[code]....

everything works fine. but my question is what if someone use a constructor again? you see if in the main method someone do this after creating the object "stand3":

HotDogStand stand3 = new HotDogStand(3, 43);
stand3 = new HotDogStand(3,40);

i know that it's logical to use setter method but this program doesn't have one. if someone do the thing i wrote above, the calculation of static variable, totalHotDogs will be all wrong. because of totalHotDogs += hotDogsPerDay; it will add another value for the same object. how can i tell the machine to ignore the second (or more) invocation of the constructor for the same object?

View Replies View Related

How To Have Unlimited Object Parameters In Constructor

Nov 21, 2014

I want to create an order system. My Problem is that I want to create it dynamic, with ArrayLists and no fixed Array size.

Basically I have already a User which is able to purchase something.

User a = new User();
Car car = new Car("blue",500);
a.purchase(new Order(new OrderThing(5,car));

This will work!

But I want something like this:

a.purchase(new Order(new orderThing(5,car), new orderThing(2,car), new OrderThing(1,car),...)

Basically I don't know how much OrderThings I want to create before I type in the OrderThings with new Order().

But in java it is before you can construct orderThings you must already know in the constructer how much objects you do want.

Now as im writing this question I got a idea of waiting for an Array of new OrderThing but it don't work. When I write

a.purchase(new Order(new orderThing(5,car), new orderThing(2,car)))

it wants a constructor which is based on Order(orderThing,orderThing)

View Replies View Related

What Does Creating ArrayList Object In A Constructor Mean

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

Super Constructor Call - Creating Object

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

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

How To Create Object To Be Null If Class Constructor Parameter Is Int

Mar 8, 2015

I have a class of Date with a constructor with 3 parameters in it. Those 3 parameters are int data type just to enter month, year, day.

I have another class called Author which has a constructor of Date diedDate; as a parameter passing to the Author constructor.

I was asked to call the Date parameter is null, call the default constructor but I thought for the Date parameter I could only enter something like 0,0,0 instead of typing in null, null, null because null is for String data type isn't it?

View Replies View Related

Create A New Instance Carte Of Object Carti Using Constructor

Mar 30, 2014

what have I done wrong n the following code? I'm trying to create a new instance carte of object Carti using the constructor and then to insert a row into a table created with SQL.The error I'm getting is:

Exception in thread "main" java.lang.NullPointerException
at Carti.Carti.InsertCarti(Carti.java:103)
at Main.main(Main.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 28 seconds)

The line Main.main(Main.java:37) is when I try to insert the row.
The line Carti.Carti.InsertCarti(Carti.java:103) is when I do the
PreparedStatement st = conn.prepareStatement("insert into Carti (Id,titlu"
+ ", descriere, autor, editie, anPublicare) values (?,?,?,?,?,?)");

Here is the code (Main and Carti Classes)

import Carti.Carti;
import Imprumut_Carti.Imprumut_Carti;
import Membrii.Membrii;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date;
import java.sql.SQLException;
import java.text.DateFormat;
 
[code]....

View Replies View Related

Insert Data From Keyboard And Check Whether Any Of Constructor Fields Remained Empty

May 12, 2015

I'm trying to use in the constructor inserts from keyboard and then check whether any of the constructors fields remained empty. Let say my constructor is:

public SomeClass(String a, String b, String c)throws SomeClassException{
if (a == null || b == null || c == null) {throw new SomeClassException("Some message"); // here is the empty test
} //...

Thus I prepared method: insertConstruct() as follows:

public static String insertConstruct(){
String lettering = null;
Scanner sc = new Scanner(System.in);
lettering= sc.nextLine();
return lettering;
}

And during creating the new object in some main method I call:

// ...
ClassName obj1;
obj1 = new ClassName(insertConstruct(),insertConstruct(),insertConstruct());
//...

The problem is not with inserting data but with leaving the field empty. When I pass any field just with keyboards Enter, the empty test doesnt return me any message about it. While it works if I build object with the constructor like:

// ...
className obj1;
obj1 = new ClassName("word a",null,"word c");
//...

What might case this failure?

View Replies View Related

Display Properties Of Each Object Instead Of Object Array List Itself?

Mar 23, 2015

If I set a Jlist to contain an array of objects, how can I display properties of each object instead of the object array list itself. Ex:

Instead of:

Person1
Person2
Person3

display values such as each person name within the Jlist:

Mike
Paul
Andrew

View Replies View Related

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 View Related

Randomly Fill 2D Array In Constructor

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

Why Can't Populate Array Of Objects From Inside Constructor

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

Array List - Not Suitable Constructor For LineItem

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

Retrieving Values Of Object

Aug 8, 2014

How do I retrieve values of an object?

public Software[] getSoftware(int index){
return software;}

The object is initialized and i get no errors when entering values .. but when i try to print by calling getSoftware I get :

[Ldd1318398project4.Software;@257f6796

View Replies View Related

How To Assign Values To Object

Apr 25, 2015

simple assignment of values to a previously initialized object?

See the method useModel ()

The idea is, assign the values to the temporary object, data

Then plunk it into this statement:

model.addRow ( data );

Simple enough?

I've been putzing with the syntax for multiple hours, over days, now.

With and without

[0];,

Netbeans keeps giving me: Illegal start of expression data is declared as an array of Object, although, in this case, it does not need to be an array. What is the correct syntax?

Java Code: //--
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
import javax.swing.JFrame;

[Code]....

View Replies View Related

Pass Private Final Class Object To Another Class Constructor

Aug 28, 2014

can we pass private final class object to another class constructor?

View Replies View Related

Populating Array Doesn't Work Inside Constructor

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







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