Passing an Array to Different Class...Netbeans Java [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
A.java
public Class A
{
String a,b;
public static void setArray(String[] array)//This is where i want the array to come
{
array[0]=a;
array[1]=b
}
}
B.java
public class B
{
String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";
public static void main(String[] args)
{
A a = new A();
a.setArray(arr1);//This is from where i send the array
}
}
I am trying to send an array from one class to another class

I've edited your code a bit. Your main problem was in class A, where you were assigning values backwards. See the updated class A. I also added a constructor to your class, but this isn't strictly necessary.
public Class A {
String a,b;
// A public method with no return value
// and the same name as the class is a "class constructor"
// This is called when creating new A()
public A(String[] array)
{
setArray(array) // We will simply call setArray from here.
}
private void setArray(String[] array)
{
// Make sure you assign a to array[0],
// and not assign array[0] to a (which will clear this array)
a = array[0];
b = array[1];
}
}
public class B {
String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";
// A a; // You can even store your A here for later use.
public static void main(String[] args)
{
A a = new A(arr1); // Pass arr1 to constructor when creating new A()
}
}

You were getting a NULL value because your String variables in class A were not initialized.
In class A you need to remove the STATIC from the method, and initialize the String a and b with something, like this:
public class A {
String a = "bye";
String b = "bye";
public void setArray(String[] array) {
array[0] = a;
array[1] = b;
}
}
In class B you should add STATIC to your array (you cannot reference a non-static variable within a static method).
public class B {
static String[] arr1 = {"hello", "world"};
public static void main(String[] args) {
A a = new A();
a.setArray(arr1);//This is from where i send the array
System.out.println(arr1[0] + " " + arr1[1]);
}
}
Also, if you want to initialize something the way you did (outside a method):
String[] arr1 = new String[2];
arr1[0]="hello";
arr1[2]="world";
you have to put the initialization within a block, like this:
String[] arr1 = new String[2];
{
arr1[0] = "hello";
arr1[2] = "world";
}
Hope this helps you

Related

Is there a way to initlalize a static field with a method?

How can I initialise an array of Strings within a class by using a method?
private static String[] strNrs2 =
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
private static String[] colo = arr();
private String[] arr(){
String[] str99 = new String[strNrs2.length];
for (int i = 0; i<strNrs2.length;i++){
str99[i]= new StringBuilder(strNrs2[i]).reverse().toString();
}
return str99;
}
I want this :
private static String[] strNrs2 =
{"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"};
To look like this:
private static String[] strNrs =
{"oreZ","enO","owT","eerhT","ruoF","eviF","xiS","neveS","thgiE","eniN"};
But I want to do it only once. Because I plan to loop through the method that will use the array, million of times. Therefore it will decrease my runtime speed considerably.
Full code:
public class IntToStr {
private static String[] strNrs2 = {"Zero","One","Two","Three","Four","Five","Six",
"Seven","Eight","Nine"};
public static String intToStr(int nr) {
StringBuilder str = new StringBuilder("");
while (nr>0) {
int pop = nr%10;
nr= nr/10;
str.append(new StringBuilder(strNrs2[pop]).reverse().toString());
//By using this str.append(strNrs[pop]); runtime will increase considerably.
}
return str.reverse().toString();
}
public static void main(String[] args) {
for (int i = 0; i<10000000;i++)
intToStr(5555555);
System.out.println("Finished");
}
}
The following array initialization:
private static String[] colo = arr();
doesn't work because arr() is a non-static method, so it can't be called in the static context of initializing a static variable.
You'll have to make arr() a static method in order for that static array initialization to work:
private static String[] arr() {
...
}

Is it possible to update a reference in a method?

I have asked this question here. I will try to make this one more specific.
class Example {
public static void main(String[] args) {
A a = null;
load(a);
System.out.println(a.toString());
// outcome is null pointer exception
}
private static void load(A a) {
a = new A();
}
}
class A {
public void String toString() {
return "Hello, world!"
}
}
So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.
Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = new A("outer");
System.out.println(a[0].toString());
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
EXAMPLE 2:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = null; // not needed, it is null anyway
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.
As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {
public static void main(String[] args) {
A[] aArray=new A[1];
load(aArray);
System.out.println(aArray[0].toString());
// outcome is Hello, world!
}
private static void load(A[] aArray2) {
aArray2[0] = new A();
}
}
class A {
public String toString() {
return "Hello, world!";
}
}
You could just have:
public static void main(String[] args) {
A a = load();
}
private static A load() {
return new A();
}
No you can't.
In java everything is passed as value not as reference.
I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}

storing passed variables into array automatically - java

I am having trouble storing a variable passed from a class into another classe's array.
I am passing a double that has been scanned in class A, to class B where I wish for the doubles to be stored in a double array, as long as the scanner in class A hasNext().
My code in class B, resembles something like this:
// I can't seem to get the passed doubles to be stored as individual elements of the array
public class B {
public final static int MAX_SIZE = 200;
public int i;
public double passedOne;
public void store() {
double[] storedOneVars = storedOneVars[MAX_SIZE]; // create a system to store variables in the array
for (i = 0; i < MAX_SIZE; i++) {
storedOneVars[i] = passedOne;
}
for (double s : storedOneVars) {
System.out.println(s);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new NumberRow().store();
}
}
I am open to suggestions :D
My Java is a little rusty, but I don't see where you are passing variable references to your class B. To add a reference to a value you can either create a constructor which excepts a parameter or pass the parameter into your store() method.
Also, you are instantiating your array incorrectly.
double[] storedOneVars = storedOneVars[MAX_SIZE];
should be
double[] storedOneVars = new double[MAX_SIZE];
You are also instantiating NumberRow but not assigning to a reference variable. Even worse is there is no NumberRow class. There is a class B. so is should be something like this:
B myB = new B();
Here is an example:
class B {
private double[] myDoubleArray;
public double[] getMyDoubleArray() {
return myDoubleArray;
}
public void setMyDoubleArray(double[] myDoubleArray) {
this.myDoubleArray = myDoubleArray;
}
public B(double[] dArray){
setMyDoubleArray(dArray);
}
public void store() {
for (double s : getMyDoubleArray()) {
System.out.println(s);
}
}
}
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double[] myd = new double[]{1,2,3};
B myB = new B(myd);
myB.store();
}
}

Print specific array object with method

I got a array of objects.
From another method i want to print one object from the array, the input to this method must be an integer, that represent the index of the object in the array.
I can't reach the array from printObject(). How do i do this?
public static void main(String[] args) {
Object []obj = new Object[2];
printObject(1);
}
public static void printObject(int i){
if (i == 0){
System.out.println(obj[0].toString());
}
if (i == 1){
Systen.out.println(obj[1].toString());
}
}
You could pass the array to printObject as a parameter (and simplify):
public static void main(String[] args) {
Object[] obj = new Object[2];
printObject(obj, 1);
}
public static void printObject(Object[] objects, int index){
if (index == 0 || index == 1) {
System.out.println(objects[index].toString());
}
}
Because it's declared inside the block of the main method, it will be known only there. Make it a class member or pass it as a parameter.
Example:
private int memberInt;
private void foo() {
memberInt = 5; // :)
int a = 7;
//..
a = 9; // :)
}
private void bar() {
a = 10; // :_(
memberInt = 10; // :)
}
The scope of the variable obj is limited to main method and will not be available in printObject method.
So to get access to variable of type Object[], make Object []obj as class member so that this member will be available through out the class or can be sent as an argument to printObject method.
Check the following code:
public class AccessingMembers
{
static Object []obj = null;
public static void main(String[] args) {
obj = new Object[2];
obj[1] = new Integer(10);//for example
printObject(1);
}
public static void printObject(int i){
if (i == 0){
System.out.println(obj[0].toString());
}
if (i == 1){
System.out.println(obj[1].toString());
}
}
}
If you run the code you'll get 10 as an answer.
either declare a global array which is accessible throughout the class or pass the array as a paramter to the method, so that it can access it.
Object []obj = new Object[2]; is a method variable and it's scope is only to that method.
Here there is one more thing using the above statement you created only two references of the object but not the instances.
//create instances
obj[0]=new Object();
obj[1]=new Object();
try this,
class Test {
static Object[] obj = new Object[2];
public static void main(String[] args) {
printObject(1);
}
public static void printObject(int i) {
obj[0]=new Object();
obj[1]=new Object();
if (i == 0) {
System.out.println(obj[0].toString());
}
if (i == 1) {
System.out.println(obj[1].toString());
}
}
}

How to implement a class constructor accepting an array of different types as an argument in Java

I have the following class:
private class Info{
public String A;
public int B;
Info(){};
public OtherMethod(){};
private PrivMethod(){};
}
And I want to create an array of this class, but I want to provide a two dimensional array as an argument to the constructor, ie:
Info[] I = new Info({{"StringA", 1}, {"StringB", 2}, {"StringC", 3}});
Is that possible? If so how would I implement it? If not, what alternatives would you suggest?
Its possible, but not using the syntax you suggested. Java doesn't support creating arrays out of constructors. Try the following:
public class Info {
public String a;
public int b;
private Info(Object [] args) {
a = (String) args[0];
b = (Integer) args[1];
}
public static Info[] create(Object[]...args) {
Info[] result = new Info[args.length];
int count = 0;
for (Object[] arg : args) {
result[count++] = new Info(arg);
}
return result;
}
public static void main(String [] args) {
Info[] data = Info.create(new Object[][] {{"StringA", 1}, {"StringB", 2}, {"StringC", 3}});
}
}
What advantage would that have compared to this?
Info[] infos = new Info[] {new Info("StringA", 1),
new Info("StringB", 2),
new Info("StringC", 3)
}.
A static factory method that accepts this input as rectangular object array, creates the instances, adds it to an Info Array and returns it ?
Info[] infos = Info.CreateInfoArray( new object[][] {
{"StringA", 1},
{"StringB", 2},
{"StringC", 3} } );
Hope this might help!
/*
Info.java
*/
public class Info{
public String A;
public int B;
Info(String s,int x){
A=s;
B=x;
};
public void show(){
System.out.println(A+" is "+B);
}
//public OtherMethod(){};
//private PrivMethod(){};
}
/*
MainClass.java
*/
public class MainClass {
public static void main(String[] args) {
Info in[] = {new Info("one",1),new Info("one",1),new Info("one",1)};
//System.out.println(in[0]);
in[0].show();
}
}

Categories