Instance variables with arrays - java

I am trying to create an instance variable that is an array. I have many methods that will produce certain statistics about the array. I'm wondering if someone can explain to me if I am going about this the correct way. I'm rather new to Java, so any pointers is greatly appreciated.
When I run the program I get errors, such like Null. I'm not looking to fix these errors now, I'm just wondering if I am going about this the correct way.
My data class:
import java.util.Arrays;
public class Stat {
private double data[];
public Stat()
{
data = new double[1];
data[0]= 0.0;
}
public Stat(double[] d)
{
d = new double[d.length];
}
public double[] getData()
{
return data;
}
public void setData(double[] d)
{
}
Main method:
double[] data = {1,2,2,3,4,5};
Stat stat1 = new Stat(data);
System.out.println(stat1.getData());
System.out.println("stat1 data = " + stat1.toString());
System.out.println("stat1 min = " + stat1.min());
System.out.println("stat1 max = " + stat1.max());
System.out.println("stat1 average = " + stat1.average());
System.out.println("stat1 mode = " + stat1.mode());
System.out.println("stat1 data = " + stat1.toString());

This constructor doesn't really do anything. You pass in an array in d, and then assign d to a different array when you say new, and additionally, d only lives on the stack until the method returns. Whenever this constructor is used data is never initialized and that's where your error is coming from.
Change:
public Stat(double[] d)
{
d = new double[d.length];
}
to something like this:
public Stat(double[] d)
{
data = d;
}
Here's what I ran on my computer:
public class Stat {
private double data[];
public Stat()
{
data = new double[1];
data[0]= 0.0;
}
public Stat(double[] d)
{
data = d;
}
public double[] getData()
{
return data;
}
}
public class JavaTest {
public static void main(String[] args) {
double[] data = {1,2,2,3,4,5};
Stat stat1 = new Stat(data);
System.out.println(stat1.getData()[0]); //outputs 1.0
}
}

Change the constructor to be
public Stat(double[] d)
{
data = d.clone();
}
Because by using the new keyword, your are creating a new empty array. Second error, you can't print directly an array. You have to print its elements, one by one using a for loop for example.
However, I suggest that you override the toString() method
#Override
public String toString(){
return Arrays.toString(data);
}
Then printing your class will output the content of the array
System.out.println("stat1 data = " + stat1);

Related

How to assign a predefined array to length of zero

I have this block of code and if the main method calls this method and if the parameter is null, then an empty array should be assigned to data. How would I go about doing this?
// Private double array data
private double data[];
// Default constructor that creates a double array having a single element of 0.0
public Stat() {
data = new double[0];
} // End of method
public class StatTester {
public void setData(double[] d) {
if (d == null) {
//where an empty array should be assigned to data
} // End of for loop
} // End of if condition
else {
double[] data = new double[d.length];
for (int c = 0; c < data.length; c++) {
data[c] = d[c];
} // End of for loop
this.data = data;
} // End of else condition
} // End of method
public static void main (String[] args) {
double[] data1 = {50.0, 60.0};
Stat stat1 = new Stat();
data1 = null;
stat1.setData(data1);
System.out.println("stat1 data = " + stat1.toString());
}
Should output:
stat1 data = [50.0, 60.0]
stat1 data = []
Thank you!
Do not redeclare data in setData.
Return as soon as you assign an empty array to data.
Demo:
import java.util.Arrays;
public class Stat {
private double data[];
public Stat() {
data = new double[0];
}
public void setData(double[] d) {
if (d == null) {
data = new double[0];
return;
}
data = new double[d.length];
for (int c = 0; c < data.length; c++) {
data[c] = d[c];
}
}
public static void main(String[] args) {
double[] data1 = { 50.0, 60.0 };
Stat stat1 = new Stat();
stat1.setData(data1);
System.out.println("stat1 data = " + Arrays.toString(stat1.data));
data1 = null;
stat1.setData(data1);
System.out.println("stat1 data = " + Arrays.toString(stat1.data));
}
}
Output:
stat1 data = [50.0, 60.0]
stat1 data = []
Not sure what your problem is.
To assign empty array (array of size 0) to data do same you do in constructor:
data = new double[0];
However, since you've already did that in construction, just do nothing if d == null.
One thing confusing about your code is that you seem to have class Stat with field data and an inner class StatTester that refers to data from Stat via this.data, and does not declare it's own field data. And method setData is in StatTester, not Stat - so your code won't compile.
I'm assuming what you actually wanted is something this:
import java.util.Arrays;
public class Stat {
// Private double array data
private double data[];
// Default constructor that creates a double array having a single element of 0.0
public Stat() {
data = new double[0];
} // End of method
public void setData(double[] d) {
if (d != null) {
this.data = java.util.Arrays.copyOf(d, d.length);
}
} // End of method
public String toString() {
return Arrays.toString(data);
}
public static void main(String[] args) {
double[] data1 = { 50.0, 60.0 };
Stat stat1 = new Stat();
stat1.setData(null);
System.out.println("stat1 data = " + stat1.toString()); // outputs empty array []
stat1.setData(data1);
System.out.println("stat1 data = " + stat1.toString()); // outputs [50.0, 60.0]
}
}
If you want to assign an empty array to data simply do what you already have: data = new double[0];
However as Java is pass by value, where you indicate you want to do this assignment will not work. The reason is the variables data and d and separate. This can be confusing as when they both point to the same array, changes can be made to the array via either reference. However what you are trying to do is not operate on the underlying array, but assign a new array back.
What you need to do is either change the return type of setData to double[] and assign it back or wrap data in another object/ array and then your assigment will work.
you need to make an array with length of zero if you want to print an empty array like [] instead of printing null value:
if (d == null) {
this.data = new double[0];
return;
}
you can also do it in other way just assigning the this.data to d like below and it work correctly but it will print null instead of []:
if (d == null) {
this.data = d;
return;
}

How to display Fibonacci numbers using a Linked list in Java

I have created a class using linked list to display 20 Fibonacci numbers. Here is my code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList(LinkedList<Integer> FibonacciLinkList) {
this.fibonacciList = FibonacciLinkList;
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
LinkedList fibonacciList = new LinkedList();
fibonacciList.display(); //This is where the error is
}
}
The problem I am having is displaying the Fibonacci numbers on the console.
I have tried to do this by using a display method but it hasn't really worked for me. I have done a lot of searching online and on SO and have tried them but they have not worked for me. It would be appreciated if you could fix my code so that it does work.
I am new to linked list and this is the first time I am coding a linked list myself and I feel that a solution to this problem will help me understand linked lists better.
As I mentioned, LinkedList is not an instance of FibonacciLinkedList, and it does not possess the display() method. Attempting to invoke it on the LinkedList object will lead to failure to compile.
The sum() method is not invoked nor does it actually do anything. That is, it does not assign anything to the fibonacciList you have.
I would recommend that you extend the LinkedList class and generate the items on instantiation. Then, using the default toString() you can display to console. After all, the class is simply an extension of the LinkedList data structure to store Fibonacci numbers up to 20.
As you extend LinkedList, you inherit the AbstractCollection.toString() method for which the "string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]")."
public class FibonacciLinkedList extends LinkedList<Integer> {
public FibonacciLinkedList(int n){
int a = 0, b = 0, c = 1;
for(int i = 1; i <= n; i++) {
a = b;
b = c;
c = a + b;
this.add(c);
}
}
public void display() {
System.out.println(this.toString());
}
public static void main(String[] args) {
FibonacciLinkedList list = new FibonacciLinkedList(20);
list.display();
}
}
I fixed your code:
import java.util.LinkedList;
public class FibonacciLinkList {
private LinkedList<Integer> fibonacciList;
public FibonacciLinkList() {
this.fibonacciList = new LinkedList<Integer>();
}
public LinkedList<Integer> sum()
{
int n, a = 0, b = 0, c = 1;
for(int i = 1; i <= 20; i++)
{
fibonacciList.add(a);
a = b;
b = c;
c = a + b;
}
return fibonacciList;
}
public void display() {
System.out.println(fibonacciList);
}
public static void main(String[] args) {
FibonacciLinkList fibonacciList = new FibonacciLinkList();
fibonacciList.sum();
fibonacciList.display();
}
}
Try this.
There is several points that you need to take care :
sum() is never called.
the look in sum() does not change fibonacciList, it only uses local variables and does nothing else with it.
display() is NOT a LinkedList function, so it will likely not work. And even if it were working, it will likely not display what you expect : you need to loop through the list and print each value.
an other fibonacciList is created in the main function, so the display (if it was working) would show the content of this local list and not the global one.

accessing objects in an array Java

I am having trouble understanding how to set and get objects in an array. Please keep it basic/simple; I am a beginner.
I cannot use a list as I am not there yet in my java class. We are supposed to use regular arrays.
I am building a program that creates solar system objects and puts planet objects in the solar system object array. I have to be able to insert the planet by index as well as get it by index.
Getting regular object info was simple but once arrays were added. It got tough. I understand better when I can comprehend how and why something works. Here is my code. Many thanks in advance!
Planet Class
public class Planet {
// private fields
private String planetName;
private int numMoons;
// param constructor
public Planet(String n, int m){
planetName = n;
numMoons = m;
}
public String toString(){
return planetName + " " + numMoons;
}
public void setPlanetName(String n){
this.planetName = n;
}
public String getPlanetName(){
return planetName;
}
public void setNumMoons(int m){
this.numMoons = m;
}
public int getNumMoons(){
return numMoons;
}
}
Here is the SolarSystem class
package project03;
public class SolarSystem {
private String solarSystemName;
private Planet[] allPlanets = new Planet[8];
private int numPlanets;
public SolarSystem(String ss, int np){
solarSystemName = ss;
numPlanets = np;
}
public void setSolarSystemName(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
/*public void setAllPlanets(String ss){
solarSystemName = ss;
}
public String getSolarSystemName(){
return solarSystemName;
}
*/
}
Finally here is my driver class that houses the main method
package project03;
public class Driver {
public static void main(String[] args) {
// creates planet object
Planet Mercury = new Planet("Mercury", 0);
Planet Venus = new Planet("Venus", 0);
Planet Earth = new Planet("Earth", 1);
Planet Mars = new Planet("Mars", 2);
Planet Jupiter = new Planet("Jupiter", 67);
Planet Saturn = new Planet("Saturn", 62);
Planet Uranus = new Planet("Uranus", 27);
Planet Neptune = new Planet("Neptune", 14);
SolarSystem ourSolarSystem = new SolarSystem("Sol-System", 8);
System.out.println("Planet name is : " + ourSolarSystem.getSolarSystemName());
//System.out.println("Moon number is :" + Mercury.getNumMoons());
}
}
You are missing a couple of methods from your SolarSystem class
public void setPlanet (Planet planet, int pos) {
allPlanets [pos] = planet; // pos is zero based
}
public Planet getPlanet (int pos) {
return allPlanets [pos]; // pos is zero based
}
Then you can use it as
ourSolarSystem.setPlanet (Mercury, 0);
You have to add methods in your solar system class to add objects to the internal array.
to populate an array , you need 2 things
1. Size
2. Elements.
Your solar system class has provisions for none at this point. Size is hardcoded to 8, which is fine for this example, ideally it should be passed in constructor while creating a solar system.
Ignoring that for a moment, you should add method in the class to add a planet.
Since this is for your learning, I am not adding exact code, just algorithm
public void addPlanet(Planet p, int pos){
//check pos is less than array size
// add planet to the index pos if pos is less than size.
}
You could also create an array outside and add it to the solar planet
public void addPlanets(Planet[] planetArray){
// replace current planet array with the array passed in input
}
The array outside can be created easily
Planet[] planetArray = new Planet[8];
planetArray[0] = Mercury ;
// and so on.

Java printing an array of objects

I know there are a lot of pages about this question, but I cannot understand it in my case.
I need to print the array of objects. For example, I have an array of objects that hold objects from the "shape" class. Do I call the toString method for each object in the array, or do I code the toString method in ObjectList to print out the instance variables? If so, how do I do that?
public class Shape{
private String shapeName;
private int numSides;
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
public class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
}
public String toString(){
// prints out the array of objects
// do I call the toString() method from the object?
// or do I print the instance variables? What am I printing?
// I'm guessing I do a for loop here
}
}
public class Driver{
public static void main(String[] args){
ObjectList list = new ObjectList();
Shape square = new Shape("square", 4);
Shape hex = new Shape("hexagon", 6);
list.add(square);
list.toString(); // prints out array of objects
}
I am aiming for it to print this:
square has 4 sides
hexagon has 6 sides
The simplest way to do this is use Arrays.toString:
Arrays.toString(myArray);
This will internally call the toString method of every element of your array.
So just override toString method in your Shape class and it should work fine.
To add further, override toString method in your class where you call Arrays.toString on your variable list :
public class ObjectList{
private Object[] list = new Object[10];
.............
public String toString(){
return Arrays.toString(list);
}
}
You can do this with bellowed code, make for loop in toString method to print each shape object.
class Shape{
private String shapeName;
private int numSides;
Shape(String shapeName, int numSides){
this.shapeName = shapeName;
this.numSides = numSides;
}
public String toString(){
return shapeName + " has " + numSides + " sides.";
}
}
class ObjectList{
private Object[] list = new Object[10];
private int numElement = 0;
public void add(Object next){
list[numElement] = next;
numElement++;
}
#Override
public String toString(){
String str="";
int i=0;
while(list[i] != null){
str += list[i]+"\n";
i++;
}
return str;
}
}
public class Driver{
public static void main(String[] args){
ObjectList list = new ObjectList();
Shape square = new Shape("square", 4);
Shape hex = new Shape("hexagon", 6);
list.add(hex);
list.add(square);
System.out.println(list);
}
}
Write a for-each statement in toString() of Object List and create a large String with '\n' characters and return it as a String . Or may be name displayListElement() will be semantically more correct in which you can simple print all the Objects in the list .
Indeed, you should call toString method for each of objects that you want to print and join them together. You can use StringBuilder to hold the string-in-the-making as follows:
public String toString() {
StringBuilder result = new StringBuilder();
for (int i = 0; i <= numElements; i++) {
result.append(list.toString() + "\n");
}
return result.toString();
}
Note that you need to increase numElements (e.g. numElements++) for each add operation as what pbabcdefp said in the comments. Also, you can use ArrayList class to manage "growing arrays".

Get back variables passed to jruby from java

This may be simple , I'll search for this but no luck
I have the code:
import org.jruby.embed.ScriptingContainer;
public class Test {
public static void main(String[] args){
ScriptingContainer container = new ScriptingContainer();
int a = 1234;
container.put("a", a);
container.runScriptlet("a = a+10 ; puts a");
System.out.println(a);
}
}
You can see that ,the output from container.runScriptlet("a = a+10 ; puts a"); is 1244
and System.out.println(a); is 1234
Now i want the a variable must be change after run from jruby ,so that the
System.out.println(a); should be 1244
How to do that ?
Your example can never work as written. int is a primitive type and will be passed by value, not by reference. That is, the value 1234 gets passed to JRuby, not "a". You can easily see this by the fact that you can give the variable a different name in container.put.
If you want just a single variable back, you can return it from your script:
public class Main {
public static void main(String[] args){
ScriptingContainer container = new ScriptingContainer();
container.put("a", 1234);
Object v = container.runScriptlet("a += 10; a");
System.out.println(v);
}
}
If you need more values, I'd recommend creating a simple bean that you can use to pass values back in an organized manner:
public class Main {
public static class Values {
private String name;
private Long age;
public void setName(String n) {
this.name = n;
}
public void setAge(Long a) {
this.age = a;
}
public String toString() {
return name + " is " + age + " years old!";
}
}
public static void main(String[] args){
ScriptingContainer container = new ScriptingContainer();
Values vs = new Values();
container.put("values", vs);
container.runScriptlet("values.age = 20; values.name = 'Tanya'");
System.out.println(vs);
}
}
As a third solution, follow the example in the JRuby Javadocs:
ScriptingContainer container = new ScriptingContainer(LocalVariableBehavior.PERSISTENT);
container.runScriptlet("p=9.0");
container.runScriptlet("q = Math.sqrt p");
container.runScriptlet("puts \"square root of #{p} is #{q}\"");
System.out.println("Ruby used values: p = " + container.get("p") +
", q = " + container.get("q"));

Categories