I want to create a function to change a value in an array, but I don't want to pass the array to the function. Here is the part of the code, data[] array created at another function.
private int[] data;
public static void main(String[] args) {
setPixel(3,2); //I'm not sure at this part?
}
public void setPixel(int i,int x){
data[i] = x; //Is there any possible way to change data[]
}
You should create a class around your main method and instantiate it within main. You then make data a variable of your class and you can access it from within the setPixel() method. This is the proper Object Oriented (OO) way of accomplishing what you're asking.
public class Data {
private int[] data;
public Data(int size) {
data = new int[size];
}
public void setPixel(int i, int x) {
data[i] = x;
}
public static void main(String[] args) {
Data instance = new Data(5);
instance.setPixel(3, 2);
}
}
Here's my answer, which is pretty much like what #zposten provided, but also address's the OP's data[] array created at another function requirement:
public class EncapsulatedArray
{
private final int[] data;
public EncapsulatedArray(final int[] data)
{
this.data = data;
}
public int getPixel(final int i)
{
return data[i];
}
public void setPixel(final int i, final int x)
{
data[i] = x;
}
#Override
public String toString()
{
return Arrays.toString(data);
}
}
To verify and demonstrate, I used:
public class EncapsulatedArrayDemo
{
public static void main(final String[] args)
{
final int[] dataFromElsewhere = { 0, 1, 2, 3 };
final EncapsulatedArray ex = new EncapsulatedArray(dataFromElsewhere);
System.out.println(ex);
ex.setPixel(2, 7 + ex.getPixel(2));
System.out.println(ex);
}
}
and obtained the following to console:
{ 0, 1, 2, 3 }
{ 0, 1, 9, 3 }
There are various reasons why wrapper classes like this (toy) example are useful, but if you are hoping to "protect" the data array from outside changes (i.e. only setPixel(int, int) is allowed to modify values in data) then you'll need something more like #zposten's answer which never lets the data array object escape from the wrapper. If you do need to use a data array created at another function then something like my solution is required - but you'll have to take other steps to ensure that the array isn't fiddled with behind the wrapper's back.
Related
Hi i am trying to solve the problem I am facing
public class exam {
public static void main(String[] args) {
test1 a = new test1();
}
int zahl(int x, int y) {
int e;
if(x>y) {
e=x-y;
}else {
e=y-x;
}
if(e==0) {
return 0;
}
int z=0;
int i=1;
while(i<=e) {
z=z+i;
i++;
}
return z;
}
}
what I want to do is to call the zahl method to the test1 class
public class test1{
private exam b;
public void init() {
b = new exam();
}
void test() {
int result = b.zahl(2, 2);
assertEquals(1, result);
}
}
this is what I have tried, but it returns nothing, even though it's supposed to show me error.
You should probably be declaring your functions with the public tag i.e. public void test() if you intend to access them from other functions outside of that package. The usual Class naming convention in Java is with capital first letter, which makes your code more readable for you and others.
For your question, I don't think you are actually invoking the test() method of the test1 class. If you want that method to get called every time, you could place it inside the default Constructor.
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
}
}
I want each element of an enum to have different variables but I can't reach them.
public class Employee {
public GENERAL[] general = GENERAL.values();
public static void main(String[] args) {
Employee e = new Employee();
e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile
}
enum GENERAL{
INCOME{
public int salary;
public int tips;
},SATIFACTION{
//some variables
},EFFICIENCY{
//some variables
};
}
}
I've tried casting to (GENERAL.INCOME) but it didn't work. Is there a way to do it? If this is not possible, what is the best work around? Thanks in advance.
Try defining variables at enum level rather than individual elements:
public static void main(String[] args) {
MainClass e = new MainClass();
e.general[GENERAL.INCOME.ordinal()].salary = 10; //this line doesn't compile
System.out.println(e.general[GENERAL.INCOME.ordinal()].salary);
}
enum GENERAL{
INCOME(0,0), SATIFACTION(0, 0), EFFICIENCY(0,0);
int salary;
int tips;
GENERAL(int salary, int tips){
this.salary = salary;
this.tips = tips;
}
}
This is because INCOME is an anonymous subclass of GENERAL, it is something like this
static class GENERAL {
public static GENERAL INCOME = new GENERAL() {
public int salary;
public int tips;
};
}
there is no way to access fields of an anonymous class in Java (except reflection)
This is the cleanest way I can do it. I still have an array that I can use to iterate. Each element of the General holds its own variables. Each element has an ordinal to use as the index number.
The problem with this approach is this cannot make use of GENERAL.values(). If a new element is added later, It must be added to the getList() method manually and in the correct order. It is easy to make mistakes when adding new elements to the code.
public class Employee {
public Object general[] = General.getList();
public static void main(String[] args) {
Employee e = new Employee();
General.Income i = (General.Income) e.general[General.Income.ordinal];
i.salary = 10; //eclipse doesn't let me to combine these 2 lines into 1 expressions.
System.out.println(i.salary);
// following lines demonstrates that the salary of the e.general[General.Income.ordinal] is changed. Not just the i.
General.Income t = (General.Income) e.general[General.Income.ordinal];
System.out.println(t.salary);
}
public static class General {
public static Object[] getList() {
Object general[] = { new Income(), new Satisfaction(), new Efficiency() };
return general;
}
public static class Income {
public static final int ordinal = 0;
public int salary;
public int tips;
}
public static class Satisfaction {
public static final int ordinal() {return 1;}//using method instead of int saves memory. (8 bytes I think. Neglettable).
// some variables
}
public static class Efficiency {
public static final int ordinal = 2;
// some variables
}
}
}
If each enumeration would contain a single value, why not use that?
You can even add a method to retrieve some descriptive name:
enum General {
INCOME, SATIFACTION, EFFICIENCY;
int value = 0;
String getName() {
switch(this) {
case INCOME:
return "salary";
case SATIFACTION:
return "etc";
}
}
}
These can be set/get by General.values()[i].value and General.INCOME.value or add setValue(int value) and getValue() methods and make value private.
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();
}
}
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();
}
}