Print specific array object with method - java

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());
}
}
}

Related

Trying to increment local variable from a separate method but not working. Confusion about Activation Stack/Record

public class Demo {
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
int size = 0;
inc(size);
System.out.println(size);
}
public int inc(int size){
size++;
return size;
}
}
When I call the code above, the number zero is returned.
Even declaring size as a class attribute instead of a local variable does not solve the problem. I understand that when a method is complete, the corresponding record (containing local variable and such) is popped off of the activation stack. But, if the size variable is declared in the init() method, and then incremented and returned in a separate method (inc()), shouldn't size be equal to 1?
When incrementing you do not assign the value to anything, it increments it, but it does not store it anywhere so the value remains 0, try doing like this.
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
size = inc(size);
System.out.println(size);
}
public int inc(int size)
{
size++;
return size;
}
}
or like this
public class Demo
{
public static void main(String[] args)
{
Demo instance = new Demo();
instance.init();
}
public void init()
{
int size = 0;
System.out.println(inc(size));
}
public int inc(int size)
{
size++;
return size;
}
}
size = inc(size);
will solve your problem, since you are not using a public scoped variable.
If you want to make this a bit elegant (at least I think this will be a bit more handy), then you need to declare a variable as a class variable.
I will illustrate this to you:
public class Demo {
int size; //global range variable
public static void main(String[] args){
Demo instance = new Demo();
instance.init();
}
public void init() {
this.size = 0;
inc();
System.out.println(this.size);
}
public void inc(){
this.size++; //will increment your variable evertime you call it
}
}

Trying to assign value to array elements and return it in another class to work with but not working

I am having diffculty with trying to assign value to array elements based on a userinput and checking the array element's value in another class. When I do that I get null and I am not sure why and how to fix it.
I have no expereince with java, just started learning it and doing it as part of uni course.
Any help is appreciated and thank you.
Class 1
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
Class 2
public class MainProgram {
public static void main(String[] args) {
UserInterface input = new UserInterface();
input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
String check[] = checkError.getError();
if (check[0] == ("Hello")) {
System.out.println("yh");
}
}
}
I think you're confusing your method calls a bit. In class 2, you have a line:
String check[] = input.getError();
That should probably be:
String check[] = checkError.getError();
As the getError() method is in your first class (ErrorHandling) and not the UserInterface class.
Also, you assign Hello to errorMessage[0] and not hey, so that might be failing in your last few lines in class 2.
If you're just starting out with Java I recommend reading up on Class Structure to understand this (as well as Arrays).
**EDIT
String comparison in Java doesn't work using the == operator. As they are objects and not primitive data types, you must use .equals.
check[0].equals("Hello")
Invoke checkError.inputCheck() in the main program otherwise errorMessage will not get initialized.
Some tweaks in your code that will help to execute:
Class 1
public class ErrorHandling {
String[] errorMessage = new String[4];
public void inputCheck() {
UserInterface input = new UserInterface();
int[] checkUserInput = input.getInput();
// If you want to use askZigZag... use it somewhere inside this function
// since you have already declared the object of UserInterface.
if (checkUserInput[0] < 20 || checkUserInput[0] > 80) {
errorMessage[0] = "Hello";
}
if (!(checkUserInput[1] <= 10 && checkUserInput[1] % 2 == 0)) {
errorMessage[2] = "Hey";
}
}
public String[] getError() {
return errorMessage;
}
}
Class 2
public class MainProgram {
public static void main(String[] args) {
// UserInterface input = new UserInterface();
// input.askZigZag();
ErrorHandling checkError = new ErrorHandling();
checkError.inputCheck();
String check[] = checkError.getError();
if (check[0].equals("Hello")) {
System.out.println("yh");
}
}
}

Java: Objects that always have the same content?

I want to desrcibe my question with an example:
Base.java:
public class Base {
//NO annotations
public AnyClass anyObj;
public Base(){}
}
DerivedOne .java:
public class DerivedOne extends Base{
#SomeAnnotionsOne
public AnyClass anyObjWithAnnotations;
public DerivedOne (AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
DerivedTwo.java:
public class DerivedTwo extends Base {
//These annoations differ from #SomeAnnotionsOne
#SomeAnnotionsTwo
public AnyClass anyObjWithAnnotations;
public Derived_Two(AnyClass anyObj){
this.anyObj = anyObj;
anyObjWithAnnotations = this.anyObj;
}
}
So i just want anyObjWithAnnotations always be equal to anyObj.
Example main:
public static void main(String[] args){
DerivedOne derivedObj = new DerivedOne(new AnyClass());
derivedObj.anyObj = null;
if(derivedObj.anyObjWithAnnotations == null){
System.out.println("anyObjWithAnnotations : is null");
}
}
Nothing is printed. anyObj is null, anyObjWithAnnotations isn't.
My Question:
Is it possible that anyObj is always the same as anyObjWithAnnotations??
So even if i set one of them to null or create a new instance of AnyClass with new the other variable should have the same new content.
EDIT:
Changed whole example to clarify the problem.
You can use below code, where i am creating object 1 time only and then assign its reference into second object. In this way if a value is changed in one object, in example t1, it will be reflected into t2 as well.
class Test {
private int val;
public Test(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
public class TestSame {
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2=t1;
System.out.println(t1.getVal());
System.out.println(t2.getVal());
t1.setVal(20);
System.out.println(t1.getVal());
System.out.println(t2.getVal());
}
}
O/P :-
10
10
20
20
You can also check that both t1 and t2 has same hashcode value
System.out.println("t1 hashcode "+ t1.hashCode());
System.out.println("t2 hashcode "+ t2.hashCode());
Looks like you need a singleton.
public class Singleton {
private int val = 0;
public void setVal(int val) {
this.val = val;
}
public static final Singleton INSTANCE = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return INSTANCE;
}
}
Usage example:
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
s1.setVal(42);
If singleton is too much for your case you can use approach:
Object obj1 = new Object();
final Object obj2 = obj1;
since obj2 is final reference - you will not be able to change(reassign) it. So, obj2 and obj1 will refer the same Object instance. But it is possible to reassign obj1 reference. If you set final both obj1 and obj2 - you'll get exactly what you want.
final Object obj1 = new Object();
final Object obj2 = obj1;

Accessing the max element from a list in another class - JAVA

for educational purposes I am trying to understand how to access a list's maximum element(originally in class B) (in this case from a Double list) through another class e.g class A. The list is used in a different class in which elements are added to it (e.g class C). However, when I add something like this to my class A to access my Max element, it does not seem to work: // help is appreciated :) and the error I usually get is noSuchElementException
just a method of class A
void printMax () {
B b = new B();
Double result;
result = Collections.max(b.array);
System.out.println("MAX:" +result);
}
here is my class B:
public class B {
public ArrayList<Double> array;
B() {
array = new ArrayList<Double>();
}
public void doSomething() {
int i;
for(i = 0; i < array.size(); i++) {
System.out.println("Doubles:" +array.get(i));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new B().doSomething();
}
}
Here is my class C that adds to my ArrayList.
Class C {
public String line;
C () {
}
public void linePicker() {
B b = new B();
Scanner dScanner = new Scanner(line);
while (dScanner.hasNext()) {
if (dScanner.hasNextDouble()) {
b.array.add(dScanner.nextDouble());
break;
} else {
dScanner.next();
}
}
dScanner.close();
b.doSomething();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new C().linePicker();
}
}
According to the javadocs (http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max(java.util.Collection,%20java.util.Comparator)), it throws that exception when the Collection is empty. You initialize b.array, but haven't added to it yet before calling max().

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();
}
}

Categories