my friend has programmed a Breakout game in java. I know C++, which tranfers relatively well to java.
I had a problem when trying to insert a MultiBall brick.
Here are the relevent bits of my function:
private Balle[] balle;
public BriqueMultiBalle(Balle[] bal) {
super();
balle = bal;
SCORE = 100;
}
public void touched() {
visible = false;
balle[Balle.getNInstance()].makeVisible();
}
I get no error but I found out when debugging that balle corresponds to a null pointer. I tried using these different declarations, however, none of them worked:
1.
public BriqueMultiBalle(Balle[] bal) {
super();
for(int i = 0; i < 6; i++)
{
balle[i] = bal[i];
}
SCORE = 100;
}
2.
public BriqueMultiBalle(Balle[] bal) {
super();
balle = new Balle[](bal);
SCORE = 100;
}
However, these methods do not work.
Thanks,
Ghi102
You are getting a null pointer on balle because you never initialize the array, you leave it as
private Balle[] balle;
Try initializing you code
balle = new Balle[bal.length];
for(int i = 0; i < bal.length; i++){
balle[i] = bal[i];
}
Here's an example I wrote using an int array. Same concept, just apply it to your object.
public static void main(String[] args) throws Exception {
int[] arrayInts;
int[] originalInts = { 1, 2, 3, 4, 5 };
arrayInts = new int[originalInts.length];
for(int i = 0; i < originalInts.length; i++){
arrayInts[i] = originalInts[i];
}
originalInts[0] = 10;
for (int i : arrayInts) {
System.out.println(i);
}
}
Related
I have an assignment for object-oriented programming class. I've been trying to take the values of an array that were initialized in a constructor, and use the values from that constructor to print them in a different method called printArrayValues. I cannot seem to 'call' or return the values in the method.. I've been troubleshooting for hours and I'm getting frustrated.
The assignment's steps are as follows:
The constructor for the ExerciseOne class initializes and instantiates myArray as an array of ten integers, and initializes the elements of the array with the values 1 through 10, using a for-loop.
You must assign the values in terms of the for-loop index variable, for example, i.
The class has a method called printArrayValues that uses a for-loop and System.out.print() statement to print out the values of the elements of the array, as shown in the sample output.
This method has no parameters, and no return value.
I've tried creating a new variable in the constructor, and then calling it in the method, but it's not working.
public class ExerciseOne {
public int[] myArray;
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray = new int[i];
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a] + 1));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
//
//public void displayArrayProduct() {
// for (int : myArray) {
//
// }
//
//}
}
I got frustrated and just created the loop, to initialize it, in the method. This is incorrect for the assignment, but I wanted to move on. Honestly I'm very lost at this point and I'm sorry if that makes it more difficult to help me.
You can try this code.
public class ExerciseOne {
public int[] myArray = new int[10];
public static void main(String[] args) {
ExerciseOne aExerciseOne = new ExerciseOne();
aExerciseOne.printArrayValues();
}
ExerciseOne() {
for (int i = 0; i < myArray.length; i++) {
this.myArray[i] = i+1;
}
}
public void printArrayValues() {
System.out.print("myArray = {");
for (int a = 0; a < myArray.length; a++) {
System.out.print((myArray[a]));
if (a < 9) {
System.out.print(",");
}
else {
System.out.print("};");
}
}
}
}
Output: myArray = {1,2,3,4,5,6,7,8,9,10};
You are initializing the same array twice. Your program will work the same if you use any of below :
myArray = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9 , 10};
or
myArray = new int[10]; for (int i = 0; i < myArray.length; i++) { this.myArray[i]=i+1; }
as your array is not 2d array so you cant assign another array on elements of array.
this.myArray = new int[i]; // not correct
I've written and tested the below and it returns the output you need. Please note that it's been written in C# for a console application. If it helps then please remember to vote for me.
Create your ExerciseOne class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
public class ExerciseOne
{
int[] eo;
public ExerciseOne()
{
eo = new int[10];
for (int i = 0; i <= 9; i++)
{
eo[i] = i + 1;
}
printArrayValues();
}
public void printArrayValues()
{
foreach (var item in eo)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
Then call the class like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
static void Main(string[] args)
{
ExerciseOne one = new ExerciseOne();
}
}
}
I am quite new to programming and I am just starting using java. My task was to write a program using quick sort, I managed to write it but it always gives me an index out of bounds. Could anyone take a look at my code and help me by identifying what I am doing wrong? Thanks
This is the code for the main class.
package quicksort;
public class Quicksort {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] x = {5,3,10,1,9,8,7,4,2,6,0};
quicksort_class q = new quicksort_class(x);
q.sort();
for(int i = 0; i < 11-1; i++)
{
System.out.println(x[i]);
}
}
}
This is the code for quicksort_class.
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
public void partitionstep(int leftlimit, int rightlimit)
{
int LPointer = leftlimit;
int RPointer = rightlimit;
Random random = new Random();
int midpoint = random.nextInt(11);
int checknumber = array1[midpoint];
while(LPointer < RPointer)
{
while(array1[LPointer] <= checknumber)
{
LPointer = LPointer + 1;
}
while(array1[RPointer] >= checknumber)
{
RPointer = RPointer --;
}
swap(LPointer, RPointer);
partitionstep(leftlimit, midpoint - 1);
partitionstep(midpoint + 1, rightlimit);
}
}
public void swap(int x, int y)
{
int temp = array1[x];
array1[x] = array1[y];
array1[y] = temp;
}
public void sort()
{
partitionstep(0, array1.length - 1);
}
}
Your midpoint value should be calculated based on your leftLimit and rightLimit. It should not be a random value based off of the fixed value 11.
I have been looking at questions of how to add elements to an array How can I dynamically add items to a Java array?.
I do not understand how to add objects of a class type, not a datatype like String. How am I supposed to do this, when the object patient has various datatypes? What I can't get my head around, is how to put the attributes of a Patient object into an array.
Class Patient{
public Patient(String ptNo, String ptName, int procType) throws IOException
{
Patient.patientNo = ptNo;
Patient.patientName = ptName;
Patient.procedureType = procType;
}
}
Another class:
public static void main(String[] args) throws IOException
{
Patient [] patients;
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients.add(p);
}
}
I understand I am missing the obvious, and only come here, after exhausting other resources.
You need to specify the array size like below
Patient [] patients = new Patient[2];
Then now add the elements like below
patients[i] = new Patient(null, null, 0)
The complete code like below
for (int i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0);
}
You need to access an array using the indexes
patients[i] = p;
but before that you need to initialize it as well.
Patient [] patients = new Patient[10]; // random init
Since you want them to be dynamic, try to use an ArrayList and keep adding the objects to it.
List<Patient> patients = new ArrayList<>();
patients.add(p);
Arrays are accessed via index:
Please modify your code like this.
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[10];
Patient p = new Patient(null, null, 0);
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
}
You are using an array and not an ArrayList thus add them by specifying the index
for (i = 0; i < 2; i++)
{
patients[i] = p;
}
EDIT
If you really want to assign the same object in the string you can even skip the object reference, like
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
int i = 0;
for (i = 0; i < 2; i++)
{
patients[i] = new Patient(null, null, 0); // No need for p now
}
}
First you need to initialize an array to be of a specific size.
Patient [] patients = new Patient[2];
Secondly, you need to use index when assigning a value.
patients[i] = p;
Finally;
public static void main(String[] args) throws IOException
{
Patient [] patients = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
}
First:
Some fixes:
class Patient
{
public String patientNo;
public String patientName;
public int procedureType;
public Patient(String ptNo, String ptName, int procType)
{
this.patientNo = ptNo;
this.patientName = ptName;
this.procedureType = procType;
}
}
Since you want your patients to be unique not the same as Patient.sth is class' property (common to all instances).
Now array and inserting:
Patient patients[] = new Patient[2];
for (int i = 0; i < patients.length; i++)
{
patients[i] = new Patient(null, null, 0);
}
but again do not fill array with the same objects. In addition not to be bound to fixed array size - use Vector (for example)
Update: about class members / aka static object members
These 2 code samples are completely different things:
class X
{
public String abc;
public void someMember()
{
this.abc = ;
}
}
and
class X
{
public static String abc;
public void someMember()
{
X.abc =
}
}
You must distinguish between what is unique to an abject and what is common to a class (ie available to all instances - common to them).
With static keyword you declare class members (they will be common foa all instances). You cannot use them with 'this' keyword which is reserved for instance members from the first example.
Here is what you must read class vs instance members
I have been developing an implementation of the neighbourhood algorithm in Java for a physics project I am working on. I'm brand new to Java so I apologize for any idiocy that results.
I have been getting the error
''
incompatible types
found : void
required: java.util.List<VoronoiPoint>
'' on line 22 from the Java compiler in attempting to compile the program shown below. I cannot figure out why the variable ''thelist'' somehow turns into a void when I declared it to be of type List<VoronoiPoint>. If anybody can explain to me what is going on it would be much appreciated!
import java.lang.Double;
import java.util.*;
public class VoronoiTiling
{
public static void main(String args[])
{
Integer n = 10; //Number of dimensions of model parameter space
Integer ns = 20; //Number of points per iteration
Integer nr = 4; //Number of cells to populate
Integer iterations = 5; //Number of iterations
List<VoronoiPoint> thelist = VoronoiList.startlist(ns,n);
//System.out.println(thelist);
//System.out.println(thelist.get(1).misfit);
for (Integer i=0 ; i<thelist.size() ; i++)
{
thelist.get(i).setmisfit();
}
List<VoronoiPoint> orderedlist = Collections.sort(thelist);
Double distance = EuclidianDistance((thelist.get(1)).location,(thelist.get(2)).location);
System.out.println(distance);
}
public static Double EuclidianDistance(Double[] point1, Double[] point2)
{
Double distance=0.0;
for (int i = 0; i < point1.length; i++)
{
distance = distance + Math.pow((point1[i]-point2[i]),2);
}
return Math.sqrt(distance);
}
}
The other classes I used are here:
The VoronoiList class:
import java.util.*;
public class VoronoiList
{
public static List<VoronoiPoint> startlist(Integer ns, Integer n)
{
List<VoronoiPoint> thestartlist = new ArrayList<VoronoiPoint>();
for (int i = 0; i < ns; i++)
{
thestartlist.add(new VoronoiPoint(0.,n));
}
return thestartlist;
}
}
The VoronoiPoint class:
import java.util.Random;
public class VoronoiPoint implements Comparable<VoronoiPoint>
{
Double[] location;
private Random generator = new Random();
Double misfit = -1.;
//***************************************************************
public VoronoiPoint(Double misfit, Integer n)
{
location = new Double[n];
ParameterBoundaries boundaries = new ParameterBoundaries(n);
for(int i = 0; i < n; i++)
{
location[i] = boundaries.getboundaries(2*i)+2*generator.nextDouble();
}
}
//***************************************************************
//public Double[] getlocation()
//{
//return location;
//}
public void setlocationi(Integer i, Double j)
{
location[i] = j;
}
//***************************************************************
public void setmisfit()
{
Integer n = location.length;
Double tempmisfit = 0.0;
for(Integer i = 0; i < n; i++)
{
tempmisfit = tempmisfit + Math.pow((location[i]),2);
}
misfit = Math.sqrt(tempmisfit); // Temporarily just distance to centre
}
//public Double getmisfit()
//{
//return misfit;
//}
public int compareTo(VoronoiPoint b)
{
if (this.misfit<b.misfit) return -1;
else if (this.misfit==b.misfit) return 0;
return 1;
}
}
And the parameter boundaries class:
public class ParameterBoundaries
{
private Double[] boundaries; /*Set to 2n where n is dimensions of parameter space,
* it just makes it easier*/
public ParameterBoundaries(Integer n)
{
boundaries = new Double[2*n];
for(Integer i = 0; i<n; i++)
{
boundaries[2*i] = -1.0;
boundaries[2*i+1] = 1.0;
}
}
public Double getboundaries(Integer i)
{
return boundaries[i];
}
}
Collections.sort(..) sorts the original list. It doesn't return a new list. (Its return type is void)
Your code is wrong. Collections.sort() is an in-place sort function; it modifies the given list argument and returns nothing (void).
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++) {
// ...