Using an array from another class - java

This seems really simple but I can't find a way to make this work in a program I'm making. I have two classes, and in one of them, I've created an array, that I want to access in another class.
This is the main class...
public class main {
public static void main(String[] args) {
boolean[] pixelValues;
pixelValues = [99];
}
}
Of course, I'm omitting a lot, but this is the code I'm having trouble with. There's a second class that goes a little like this...
public class pixelAssign {
public pixelAssign(posX, posY) {
main.pixelValues[ {some number} ] = {some value};
}
}
My problem is that I'm having trouble accessing the pixelValues array that I created in my main class from a function I made in the second bit of code. I've been getting an error in the second bit of code that say (1), says that variable can't be found, and (2), I'm missing an identifier (?). The code in this is a bit unfinished, but the function in the second bit would be called from the main class later.
Any help would be much appriciated!

Putting Paul's and SANM2009's answers together:
You should:
public class main {
static int[] pixelValues;
public static void main(String[] args) {
pixelValues = [99];
}
}
public class pixelAssign {
public pixelAssign(posX, posY) {
main.pixelValues[0] = 98;
}
}
That should work IF and only IF classes main and pixelAssign are in the same package! If not, pixelValues would not be visible.
If you want to hold with Java Good Practices:
First letter of classes are always Uppercase, so Main and PixelAssign
Often is a good practice to instante classes and use the objects. Otherwise you have to use static.
Set pixelValues as private or protected and create method:
public class Main {
private int[] pixelValues;
public Main() {
pixelValues = [99];
}
public void setPixelValue(int position, int value) {
pixelValues[position] = value;
}
public static void main(String[] args) {
Main main = new Main();
new PixelAssign(main);
}
}
public class PixelAssign {
public PixelAssign(Main main, posX, posY) {
main.setPixelValue(0, 98);
}
}

Why don't you create your function so that it accepts the array as a parameter. you can then send the array to classB from ClassA.
There seems to be another issue here.
pixelValues is meant to be an array of Boolean or some numbers (int)?
boolean[] pixelValues;
pixelValues = [99];
As for the function:
public pixelAssign(myArray, posX, posY) {
}
So when calling the function, use
pixelAssign(pixelValues, posX, posY)

Perhaps you have changed the code to make it more concise but it looks like you are simply declaring the array in the wrong scope. Could you change it to this;
public class main {
boolean[] pixelValues;
public static void main(String[] args) {
pixelValues = [99];
}
}

Related

where to declare classes and functions in java

public class demo
{
public static void main(String[] args)
}
I just started to learn java, I have c++ experience, and the layout confuses me. for example if I declare a function in the demo class would that make it a function or method. also if I want to declare a class can I declare it outside the demo class or it must be inside the demo class.
thank you.
You have already declared it. The thing you are missing is your function body.
public static void main(String[] args)
should be
public static void main(String[] args){
//DO Some Stuff
}
Now here is some additional info:
The main function will be started whenever the application is started and the
String[] args
are the arguments that you are going to pass while starting the application.
You can declare as many functions as you want within your class
public class demo{
public static void main(String[] args){
//Do Some Stuff
}
private void someFunction(){
//Do Some Stuff
}
}
For more you can start learning some basics from the internet. There are tons of tutorials. Hope that helps. :)
you can write code like that
public class Emp{
//Instance variable or class level variable even variable as static
String id;
String name;
//static variable
static int count=0;
{
//non static block
}
static{
// static block
}
public Emp(){
//default constructor
}
//parameterized constructor
public Emp(String id, String name){
this.id=id;
this.name=name;
}
// Non-Static Method
public String getId(){
return id;
}
public String getName(){
return name;
}
//Main method
public static void main(String[] args){
//Instance of class
Emp emp=new Emp("1","Xyz");
System.out.println(emp.getId());
System.out.prinln(emp.getName());
}
}
In Java there are no functions. There are only methods.
You can declare methods inside of class definitions. And methods can be static or not static. Just like in C++.
Also there's no need for header files.
Example:
public class Demo {
// This is a constructor
public Demo() {
}
// This is a non-static method
public void method() {
}
// This is a static method.
// (It's also a special entry point to start the program)
public static void main(String[] args) {
}
}
I think it's safe to say that Java is much simpler than C++.
Ps. I capitalized Demo because according to Java's camel case convention, classes should start with an uppercase letter and methods with lowercase.

Why can't I use an element of array to call its method?

public class Main {
public static void main(String[] args) {
Object[] array = new Object[1];
Piece piece = new Piece();
array[0] = piece;
array[0].move();
}
}
class Piece{
public void move(){
System.out.println("hello");
}
}
Line 6 doesn't not work and I am not sure why. Shouldn't array[0] give me piece and piece.move() call the method in the class?
You are casting Piece as Object when you add it to the Object array.
Try this:
public class Main {
public static void main(String[] args) {
Piece[] array = new Piece[1];
Piece piece = new Piece();
array[0] = piece;
array[0].move();
}
}
class Piece{
public void move(){
System.out.println("hello");
}
}
It's because on line array[0] = piece; you are assigning Piece object to Object which is valid because Object is the parent class of all.
But when you do array[0].move(); you are trying to call the move() method from reference of Object class.
This is not possible because move() method is not declared in Object class.
Thus you need to cast like below:
((Piece)array[0]).move();
When you store a Piece as Object the compiler does not know anymore that it is a Piece. You have to explicitly tell it (cast it ((Piece)array[0]).move();).
Alternatively store objects in Piece[] array.
I assume the real motivation is storing different pieces types. In this case they all have to have the same base type. This can be achieved by having all pieces types extend the same base class, or implement a common interface:
public class Main {
public static void main(String[] args) {
Movable[] array = new Movable[2];
APiece aPiece = new APiece();
BPiece bPiece = new BPiece();
array[0] = aPiece;
array[0].move();
array[1] = bPiece;
array[1].move();
}
}
interface Movable {
void move();
}
class APiece implements Movable{
#Override
public void move(){
System.out.println("APiece moved ");
}
}
class BPiece implements Movable{
#Override
public void move(){
System.out.println("BPiece moved ");
}
}

Importing a Java custom class into another program

I am a first year comp sci student and going through my first round of textbook problems, all dealing with the System.out.println method (no, im not looking for help on homework problems. i've satisfied (as far as i know right now) the requirements of the problem, am just looking to gain some extra information).
The first problem asked me to write a program that would output this:
//////////////////////
|| Victory is mine! ||
\\\\\\\\\\\\\\\\\\\\\\
This was no problem. I wrote the following code:`
public class Stewie {
public static void main(String[] args) {
line();
qoute();
line2();
}
public static void line() {
System.out.println("//////////////////////");
}
public static void qoute() {
System.out.println("|| Victory is mine! ||");
}
public static void line2() {
System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
}
}`
Later in the text, it asks me to write a program that prints the above figure 5 times in a row. This is also not a problem, I just rewrote the code from the first problem, like this:
/*
*/
public class Stewie2 {
public static void main(String[] args){
newStewie();
newStewie();
newStewie();
newStewie();
newStewie();
}
public static void newStewie() {
line();
qoute();
line2();
}
public static void line(){
System.out.println("//////////////////////");
}
public static void qoute(){
System.out.println("|| Victory is mine! ||");
}
public static void line2() {
System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
}
}
That's all good and well, but I'd like to know how to import class Stewie from the first problem so I could use that in the second one without having to rewrite all the code. Can anyone help me out??
edit:re:importing a custom java class. I saw this before posting, but probably do not know enough about programming for it to be helpful to me at the moment. thank you though.
Have a look on how to create and use packages.
Because your methods in your first class are static declared, you can just call them within your second class.
package mypackage;
public class Stewie
{
public static void main(String[] args)
{
line();
qoute();
line2();
}
public static void line()
{
System.out.println("//////////////////////");
}
public static void qoute()
{
System.out.println("|| Victory is mine! ||");
}
public static void line2()
{
System.out.println("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\");
}
}
The seconds class should also be in the same package. Then, because your methods declared in the first class are static, you can directly call them to your second class.
package mypackage;
public class Stewie2
{
public static void main(String[] args)
{
Stewie.line();
Stewie.qoute();
Stewie.line2();
}
}
Now in your second class, you can extend your code with further functionality.
Note: As already mentioned, this is allowed because your methods are static.
If your method, bellow wasn't static:
public void qoute()
{
System.out.println("|| Victory is mine! ||");
}
You would get the following error message:
Non-static method 'qoute()' cannot be referenced from a static context.
So be-careful and notice the difference.

Java static main also codingBat

public class CodingBat {
public static void main(String[] args) {
System.out.println(sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b) {
return 2*a + 2* b;
} else{
return a + b;
}
}
}
So I made this code, and I'm really confused why it doesn't work unless I write static between the public int sumDouble, because I was practicing on codingBat, and to answer the question they did not involve static, but then how do they test code. Do they use the main? I mean you have to to get the code running right?
So to my knowledge, static means that every object of this class will all contain the same value.But I don't see the relevance of this error.
"Cannot make a static reference to the non-static method"
Thank you for your help :D
and I'm really confused why it doesn't work unless I write static
between the public int sumDouble,
Yes, static is required
Since the main method is static and the sumDouble() method is not, you can't call the method without creating object of class. You cannot refer non-static members from a static method.
Either make method static or create object as below and then access method.
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
Refer here for more
Either you call it through a static context, meaning like you do (or, from another class, by: ClassName.methodName(); )
Or, you have to call it as an instance method, which it is, if you don't declare it static.Then, however, you'll need an instance to call it through:
public static void main(String[] args){
CodingBat cB = new CodingBat();
System.out.println(cB.sumDouble(5,5));
}
You need to create an object in order to use this method
public class CodingBat {
public static void main(String[] args){
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b){
return 2*a + 2* b;}
else{
return a + b;}
}
}

java - can a class type parameter from a static main class be passed to another class

I have 2 classes the static main class and class B. I'm trying to pass main to B, where there is a method that sets fields.
Can this be done?
If so, could you please provide examples?
public static void main(String[] args) {
ArrayList a = new ArrayList()
class b = new class()
b.update(b);
}
class a {
public void update(ArrayList a) {
//updates the encapsulated arrayList field
}
}
The error message keeps on saying that one is static and the other is non-static, but they should be pointing the same object
I'm not entirely sure what you are trying to do, but here is an example that shows that you can pass an instance of the main class into another class:
public class A {
private String str = null;
public static void main(String[] args) {
A a = new A();
B b = new B(a);
System.out.println(a.getStr());
}
public String getStr() {
return this.str;
}
public void setStr(String str) {
this.str = str;
}
}
public class B {
public B(A a) {
a.setA("hello");
}
}
Running this code will print out hello.
main is static and public, so you can call it from any other class as any other public static method: statically.
if you have a class A that contains a
public static void main(String[] args)
method, then class B can call this method like
A.main(s);
where s is String[]
your question is far from clear, so I suggest you to add more code samples to make it clear what you're really trying to do.

Categories