I want to pass 4 arrays from a method which is in A class, to a method in B class.
I create an instance of class A in the method which is in class B to get the arrays.
The method in A class is defined as Object[] and I use:
return new Object[]{Array1,Array2,Array3,Array4};
to return the arrays.
In method of B class I get the arrays with an object defined as:
private Object outGeoObj[] = new Object[4];
I am retrieving successfully the arrays, but I want to clear the object before I use it again. I tried:
public void ClearValues(){
if (outGeoObj != null){
outGeoObj = null;
}
else{
System.out.println("Object is null");
}
}
but it doesn't work. Any suggestions?
Minimal Working Example:
Class B:
public class MainFem {
private OutGeoMesh outmesh;
private Object outGeoObj[] = new Object[4]; // [0: Xmpoint, 1: Ympoint, 2: Vec, 3: numpoints]
public MainFem() {
outmesh = new OutGeoMesh();
}
public void ClearValues(){
if (outGeoObj != null){
for(int i = 0; i < outGeoObj.length; i++) {
outGeoObj[i] = null;
}
}
else{
System.out.println("Object is null");
}
} // END Method ClearValues
public void MainStart(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel){
outGeoObj = outmesh.createOutGeomesh(Xpoint, Ypoint, nump, c2, Line, drawPanel);
int temp = (int[][]) outGeoObj[3];
System.out.println(temp[0][0]);
}// End Method MainStart
} // END CLASS MainFem
Class A:
public class OutGeoMesh {
private double Xmpoint[][][] = new double[500][200][20];
private double Ympoint[][][] = new double[500][200][20];
private double Vec[][][] = new double[500][2][20];
private int numpoints[][] = new int[500][20];
public OutGeoMesh() {
// TODO Auto-generated constructor stub
}
public Object[] createOutGeomesh(int Xpoint[][], int Ypoint[][], int nump[], int c2, int Line[][][], DrawPanel drawPanel) {
for (int j = 0; j <= c2; j++) {
for (int i = 0; i < nump[j]; i++) {
Vec[i][0][j] = i;
Vec[i][1][j] = i+1;
Xmpoint[i][0][j] = Xpoint[i][j];
Ympoint[i][1][j] = Ypoint[i][j];
numpoints[i][j] = numpoints[i][j] + 1;
} // END FOR i
} // END FOR j
return new Object[]{Xmpoint,Ympoint,Vec,numpoints};
} // END METHOD createOutGeomesh
// ---------------------------------
} // END CLASS OutGeoMesh
You need to do something like this:
Arrays.fill(outGeoObj, null);
The reason that your code doesn't work is because you are only erasing your reference to the array, but other parts of your code are still using that same array. By using Arrays.fill you can erase the contents of the array.
Related
I tried to make a deep clone via overridong the clone method, but the result is not how a deep clone behaves(blanks and oldBlanks should print differently).
It is supposed to print:
192, []
1_2, [1]
It actually prints:
192, []
192, []
An MCVE is presented.
import java.util.ArrayList;
public class Program {
static class Blank implements Cloneable {
#Override
protected Blank clone() {
Blank b = new Blank(this);
return b;
}
public Blank(String str) {
origin = str;
uradix = str.length();
String strn = str.replaceAll("_","0");
existed = Integer.parseInt(strn);
for (int i = 0; i < uradix; i++) {
int radix = uradix - i;
if (str.charAt(i) == '_'){
not_existed.add(radix-1);
}
}
}
public Blank(Blank b){
this.origin = b.origin;
this.uradix = b.uradix;
this.existed = b.existed;
for (Integer i :
b.not_existed) {
int k = i;
this.not_existed.add(k);
}
}
String origin;
int uradix;
int existed;
ArrayList<Integer> not_existed = new ArrayList<>();//remain sequence: ->, i.e. left to right
}
static Blank[] copy(Blank[] ts){
for (Blank t :
ts) {
t = t.clone();
}
return ts;
}
public static void main(String[] args) {
Blank[] blanks = {new Blank("1_2"),new Blank("_2"),new Blank("_2_")};
Blank[] oldBlanks = copy(blanks);
StringBuilder sb = new StringBuilder(blanks[0].origin);
System.out.println("before the change");
System.out.println(blanks[0].origin+", "+blanks[0].not_existed);
System.out.println(oldBlanks[0].origin+", "+oldBlanks[0].not_existed);
int index = 1;
sb.replace(index,index+1,"9");
blanks[0] = new Blank(sb.toString());
System.out.println("after the change");
System.out.println(blanks[0].origin+", "+blanks[0].not_existed);
System.out.println(oldBlanks[0].origin+", "+oldBlanks[0].not_existed);
}
}
p.s. My tutor said that a static class used in such a pattern is weird, but that should not be the problem because the problem reproduces even if I modify the class Blank outside non-static.
It's not your clone method that causes the problem, bBut rather the way you implemented your copy.
You return the original Blank[] reference and then adapt it.
If you do this:
static Blank[] copy(Blank[] ts){
Blank[] ts_copy = new Blank[ts.length];
for (int i=0; i<ts.length; i++) {
ts_copy[i] = ts[i].clone();
}
return ts_copy;
}
Then I get an output like this:
before the change
1_2, [1]
1_2, [1]
after the change
192, []
1_2, [1]
I am new to Java and I am trying to print the student numbers and numbers (cijfer in this case) on 1 line. But for some reason I get weird signs etc. Also when I'm trying something else I get a non-static context error. What does this mean and how does this exactly work?
Down here is my code:
import java.text.DecimalFormat;
import java.util.Arrays;
public class Student {
public static final int AANTAL_STUDENTEN = 50;
public int[] studentNummer = new int[AANTAL_STUDENTEN];
public String[] cijfer;
public int[] StudentNummers() {
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
studentNummer[i] = (50060001 + i);
}
return studentNummer;
}
public String[] cijfers(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
DecimalFormat df = new DecimalFormat("#.#");
String cijferformat = df.format(Math.random() * ( 10 - 1 ) + 1);
cijfer[i++] = cijferformat;
}
return cijfer;
}
public static void main(String[] Args) {
System.out.println("I cant call the cijfer and studentnummer.");
}
}
Also I'm aware my cijfer array is giving a nullpointer exception. I still have to fix this.
I am not java developer but try
System.out.print
You could loop around System.out.print. Otherwise make your functions static to access them from main. Also initialize your cijfer array.
Besides the things I noted in the comments, your design needs work. You have a class Student which contains 50 studentNummer and cijfer members. Presumably, a Student would only have one studentNummer and and one cijfer. You need 2 classes: 1 for a single Student and one to hold all the Student objects (StudentBody for example).
public class StudentBody {
// An inner class (doesn't have to be)
public class Student {
// Just one of these
public int studentNummer;
public String cijfer;
// A constructor. Pass the student #
public Student(int id) {
studentNummer = id;
DecimalFormat df = new DecimalFormat("#.#");
cijfer = df.format(Math.random() * ( 10 - 1 ) + 1);
}
// Override toString
#Override
public String toString() {
return studentNummer + " " + cijfer;
}
}
public static final int AANTAL_STUDENTEN = 50;
public Student students[] = new Student[AANTAL_STUDENTEN];
// StudentBody constructor
public StudentBody() {
// Create all Students
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
students[i] = new Student(50060001 + i);
}
}
// Function to print all Students
public void printStudents(){
for (int i = 0; i < AANTAL_STUDENTEN; i++) {
System.out.println(students[i]);
}
}
public static void main(String[] Args) {
// Create a StudentBody object
StudentBody allStudents = new StudentBody();
// Print
allStudents.printStudents();
}
}
Just make all your methods and class variables as static. And then you have access to them from main method. Moreover you have got some errors in code:
public class Student {
public static final int AANTAL_STUDENTEN = 50;
// NOTE: static variables can be moved to local ones
// NOTE: only static method are available from static context
public static int[] StudentNummers() {
int[] studentNummer = new int[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
studentNummer[i] = 50060001 + i;
return studentNummer;
}
// NOTE: only static method are available from static context
public static String[] cijfers() {
// NOTE: it is better to use same `df` instance
DecimalFormat df = new DecimalFormat("#.#");
String[] cijfer = new String[AANTAL_STUDENTEN];
for (int i = 0; i < AANTAL_STUDENTEN; i++)
// NOTE: remove `i++`, because we have it in the loop
cijfer[i] = df.format(Math.random() * (10 - 1) + 1);
return cijfer;
}
// NOTE: this is `static` method, therefore it has access only to static methods and variables
public static void main(String[] Args) {
String[] cijfer = cijfers();
int[] studentNummer = StudentNummers();
// TODO you can pring two arrays one element per line
for(int i = 0; i < AANTAL_STUDENTEN; i++)
Sytem.out.println(cijfer[i] + '-' + studentNummer[i]);
// TODO as alternative, you can print whole array
System.out.println(Arrays.toString(cijfer));
System.out.println(Arrays.toString(studentNummer));
}
}
I'm attempting to add elements into an arraylist (also append an arraylist to the other), however it seems to rewrite everything else already present in that arraylist too - so I'm left with an arraylist filled with the last element added.
Here's the method concerned:
private static ArrayList<Move> checkX(int r, int c) {
ArrayList<Move> moves = new ArrayList<Move>();
if (jumps()) { // if jumps are found && this piece can jump
for (int i = 0; i <= 1; i+=2) {
if (Character.isLowerCase(board[r-1][c+i]) && board[r-2][c+2*i] == ' ') {
}
}
} else { // if no jumps are found then move normally
for (int i = -1; i <= 1; i+=2) {
try {
if (board[r-1][c+i] == ' ') {
Move tempMove = new Move(r, c);
tempMove.addDestination((r-1), (c+i));
moves.add(tempMove);
}
} catch (Exception e) {}
}
}
for (int i = 0; i < moves.size(); i++) {
System.out.println(moves.get(i).toString());
}
return moves;
}
Move class:
public class Move {
private static ArrayList<int[]> destinations;
// private static char[][] tmpboard;
public Move(int r, int c) {
destinations = new ArrayList<int[]>();
int[] initSquare = {r, c};
destinations.add(initSquare);
}
public void addDestination(int r, int c) {
int[] destinationSquare = {r, c};
destinations.add(destinationSquare);
}
public ArrayList<int[]> getMove() {
return destinations;
}
public String toString() {
String returnStr = "";
for (int i = 0; i < destinations.size(); i++) {
returnStr += Arrays.toString(destinations.get(i));
}
return returnStr;
}
}
Every time I attempt to print out everything stored in an instance of 'moves' it seems to only print out the last element added to the list n times.
private static ArrayList<int[]> destinations;
Here's your issue. Try removing the static modifier.
What static here means that the latest additions of destinations will affect all Move instances, which makes them identical.
It's possible you were thinking of final there instead, which would make more sense.
I want to make a 2D array of Arrays, each filled with another object. What I have so far is:
class CustomCache{
boolean dirty = false;
int age = 0;
String addr;
public CustomCache(boolean a, String b, int c){
dirty = a;
addr = b;
age = c;
}
}
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
Setup[][] array = new Setup[numSets][numBlocks];
for(int i=0; i<numSets; i++){
for(int j=0; j<numBlocks; j++){
array[i][j] = new Setup(wpb);
for(int k=0; k<wpb; k++){
array[i][j].wpbArray[k] = new CustomCache(false, "", 0);
}
}//end inner for
}//end outer loop
I keep getting a
java.lang.ArrayIndexOutOfBoundsException: 0
Which means the array is empty. Any idea of how to fix it?
This is the problem:
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
This line:
CustomCache[] wpbArray = new CustomCache[wpb];
runs before the body of the constructor - while wpb is still 0. You want:
class Setup {
int wpb;
CustomCache[] wpbArray;
public Setup(int a) {
wpb = a;
wpbArray = new CustomCache[wpb];
}
}
(I also suggest changing to more meaningful names, and using private final fields, but that's a different matter.)
I am trying to write a simple DCT algorithm in java. I want my findDCT method to have as a parameter an integer array like this:
public class DCT {
private Random generator = new Random();
private static final int N = 8;
private int[][] f = new int[N][N];
private double[] c = new double[N];
public DCT() {
this.initializeCoefficients();
}
private void initializeCoefficients() {
int value;
// temporary - generation of random numbers between 0 and 255
for (int x=0;x<8;x++) {
for (int y=0;y<8;y++) {
value = generator.nextInt(255);
f[x][y] = value;
System.out.println("Storing: "+value+" in: f["+x+"]["+y+"]");
}
}
for (int i=1;i<N;i++) {
c[i]=1/Math.sqrt(2.0);
System.out.println("Storing: "+c[i]+" in: c["+i+"]");
}
c[0]=1;
}
public double[][] applyDCT() {
double[][] F = new double[N][N];
for (int u=0;u<N;u++) {
for (int v=0;v<N;v++) {
double somme = 0.0;
for (int i=0;i<N;i++) {
for (int j=0;j<N;j++) {
somme+=Math.cos(((2*i+1)/(2.0*N))*u*Math.PI)*Math.cos(((2*j+1)/(2.0*N))*v*Math.PI)*f[i][j];
}
}
somme*=(c[u]*c[v])/4;
F[u][v]=somme;
}
}
return F;
}
}
Now, how would I declare this method and to be able to pass 'int[][] f' as a parameter instead of using f[][] declared as a private variable and initialized in the constructor of the current class?
How about extracting the initializeCoefficients and changing the constructor from
public DCT() {
this.initializeCoefficients();
}
to
public DCT(int[][] f) {
this.f = f;
}
You could then use the class like
double[][] dctApplied = new DCT(yourTwoDimF).applyDCT();
Also, I wouldn't use N the way you do. I would look at the dimensions of f itself when applying the DCT.
That is, I would change
double[][] F = new double[N][N];
for (int u=0;u<N;u++) {
for (int v=0;v<N;v++) {
// ...
to something like
double[][] F = new double[f.length][];
for (int u = 0; u < f.length; u++) {
F[u] = new double[f[u].length];
for (int v=0;v<N;v++) {
// ...