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++) {
// ...
Related
I am trying to assign value of FileData's instance variable in File class
At first FileData's nextIndex should all be -1, and then it should be assigned the value of counter
I've tried get,set and FileData array to assign value but its not working and
gives NULL POINTER EXCEPTION
I've tried:
class FileData
{
int nextIndex = 0;
public void setIndex()
{
for(int i=0; i<10;i++)
{
nextIndex = -1;
}
}
}
class File
{
public static void main(String args[])
{
FileData[] FD = new FileData[10];
for(int i=0; i<5;i++)
{
FD[i].nextIndex = i;
}
}
}
When working with objects, you first have to create an instance. All I've done is add a declarator in the loop and formatted the code:
class FileData {
int nextIndex = 0;
public void setIndex() {
for (int i = 0; i < 10; i++) {
nextIndex = -1;
}
}
}
class File {
public static void main(String args[]) {
FileData[] FD = new FileData[10];
for (int i = 0; i < 5; i++) {
FD[i] = new FileData();
FD[i].nextIndex = i;
}
}
}
Note that the FileData[] FD = new FileData[10]; bit just declares an array of the type FileData, and does not yet give each object its needed storage space.
The array elements here are null:
FileData[] FD = new FileData[10];
First you need to create the objects:
for(int i=0; i < FD.length ;i++)
{
FD[i] = new FileData();
FD[i].nextIndex = i;
}
I get a nullPointerException in my program when I try to call a boolean array in a method parameter. The boolean array is created as a constant, and then initialized in a separate void method. Can someone explain to me why it can't find the boolean array (or can't find the array values)?
public static void moveTarget(Graphics g) {
if (!targetMovement)
return;
drawTarget(g, BACKGROUND_COLOR);
drawShield(g, BACKGROUND_COLOR);
This line right here is the specific part where the program fails. (nullPointerException)
int f = findTargetMissilePosition(targetMissileActive);
I specify the constants here, but do not initialize.
// Target Missile values
public static Color TARGET_MISSILE_COLOR = TARGET_COLOR;
public static int MAX_MISSILES = 10;
public static double TARGET_MISSILE_SPEED = MISSILE_SPEED;
public static double TARGET_SHOOT_PROBABILITY = .1;
public static double[] targetMissilePositionX;
public static double[] targetMissilePositionY;
public static double[] targetMissileDeltaX;
public static double[] targetMissileDeltaY;
public static boolean[] targetMissileActive;
// main method does initialization and calls startGrame
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(PANEL_WIDTH, PANEL_HEIGHT);
Graphics g = panel.getGraphics( );
initialize();
startGame(panel, g);
}
//initialize() is called above which is where the arrays are intialized
// start the main game loop which runs forever
public static void startGame(DrawingPanel panel, Graphics g) {
while(true) {
panel.sleep(SLEEP_TIME);
handleKeys(panel,g);
moveTarget(g);
drawAll(g);
moveMissile(g);
shootTargetMissile(g);
for (int i=0;i<10;i++) {
int f = findTargetMissilePosition(targetMissileActive);
moveTargetMissile(g, f);
}
shieldHitTimer--;
targetHitTimer--;
shooterHitTimer--;
}
}
// above is the first time that line of code appears and does not appear to have an issue.
// reset all parameters to start over
public static void reset(Graphics g) {
g.setColor(BACKGROUND_COLOR);
g.fillRect(0,0,PANEL_WIDTH,PANEL_HEIGHT);
initialize();
}
//Here the arrays are initialized
// initialize parameters for the start of the program
public static void initialize() {
shooterPositionX = SHOOTER_INITIAL_POSITION_X;
gunAngle = 0;
targetPositionX = PANEL_WIDTH/2;
missileActive = false;
hitCount = 0;
shooterHitCount = 0;
hitDisplayString = "Hits: ";
targetDeltaX = 0;
targetHitTimer = 0;
shieldHitTimer = 0;
shooterHitTimer = 0;
boolean [] targetMissileActive = new boolean [9]; // might change??
int [] targetMissilePositionX = new int [9];
int [] targetMissilePositionY = new int [9];
int [] targetMissileDeltaX = new int [9];
int [] targetMissileDeltaY = new int [9];
for (int i=0; i<9; i++) {
targetMissilePositionX[i] = 0;
targetMissilePositionY[i] = 0;
targetMissileDeltaX[i] = 0;
targetMissileDeltaY[i] = 0;
targetMissileActive[i] = false;
}
}
// draw everything in its current position
public static void drawAll(Graphics g) {
g.setColor(Color.BLACK);
g.drawString("Project 3 by Benjamin Koch",10,15);
g.drawString(hitDisplayString,10,30);
int f = findTargetMissilePosition(targetMissileActive);
drawTargetMissile(g, TARGET_MISSILE_COLOR, f);
drawShooter(g,SHOOTER_COLOR);
if (targetHitTimer > 0)
drawTarget(g, SHIELD_HIT_COLOR);
else
drawTarget(g,TARGET_COLOR);
Color shieldColor = BACKGROUND_COLOR; // default: do not draw
if (shieldActive) {
if (shieldHitTimer > 0)
shieldColor = SHIELD_HIT_COLOR;
else
shieldColor = SHIELD_COLOR;
}
drawShield(g, shieldColor);
}
public static int findTargetMissilePosition (boolean[] data) {
for (int i=0;i<MAX_MISSILES;i++) {
if (data[i]==false) {
return i;
}
}
return -1;
}
Inside your initialize() function, you're creating local variables but not initializing the global ones.
targetMissileActive = new boolean [9];
targetMissilePositionX = new int [9];
targetMissilePositionY = new int [9];
targetMissileDeltaX = new int [9];
targetMissileDeltaY = new int [9];
for (int i=0; i<9; i++) {
targetMissilePositionX[i] = 0;
targetMissilePositionY[i] = 0;
targetMissileDeltaX[i] = 0;
targetMissileDeltaY[i] = 0;
targetMissileActive[i] = false;
}
This will reference the variables to the global one.
Here's my code:
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
}
What do I need to add in order to generate a random string from the list and print it in the console?
You can randomly select a value from the list with something like:
int index = new java.util.Random().nextInt(eMinor.size());
String value = eMinor.get(index);
and then print it to the console with:
System.out.println(value);
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
Random rand = new Random()
int random = rand.nextInt(eMinor.size());
String note = eMinor.get(random);
System.out.println(note);
}
e minor is one of my favorite keys, so I'll answer. You need a random number generator:
Random ran = new Random();
int x = ran.nextInt(eMinor.size() - 1)
System.out.println(eMinor.get(x));
You could generate multiple notes with a loop:
Random ran = new Random();
for (int i = 0, i < 10; i++) {
int x = ran.nextInt(7)
System.out.println(eMinor.get(x));
}
You could do something like this:
int min = 3;
int range = 3;
Random random = new Random();
int length = min + random.nextInt(range);
String randomString = "";
for (int i = 0; i < length; ++i)
{
randomString += eMinor.get(random.nextInt(eMinor.size() - 1));
}
System.out.println(randomString);
You can use a simple model, but to complex application is necessary more attention with Random class;
enter code here
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int f = 0; f < 3; f++) {
System.out.printf("------------ list %s ------------\n",f);
for (String value : generateList(eMinor)) {
System.out.println(value);
}
}
}
private static List<String> generateList(ArrayList<String> eMinor) {
List<String> tempList = new ArrayList<>();
Random random = new Random();
while (tempList.size() != eMinor.size()) {
String value = eMinor.get(random.nextInt(eMinor.size()));
if (!tempList.contains(value)) {
tempList.add(value);
}
}
return tempList;
}
}
You may use the below complete example:
/*
* Created by Mohammed.Kharma on 2/9/2016.
*/
import java.util.Random;
import java.util.ArrayList;
public class Scrambler {
public static int[] Scramble(final int key, final int elementsCount) throws NegativeArraySizeException {
if (elementsCount < 0) {
NegativeArraySizeException ex = new NegativeArraySizeException("scrambler elementCount");
throw ex;
}
Random rand = new Random(key);
int[] order = new int[elementsCount];
for (int i = 0; i < elementsCount; i++) {
order[i] = i;
}
int count = elementsCount;
while (--count > 0) {
int nextRandom = rand.nextInt(count + 1); // 0 <= k <= count (!)
int temp = order[count];
order[count] = order[nextRandom];
order[nextRandom] = temp;
}
return order;
}
public static void main(String[] args) {
ArrayList<String> eMinor = new ArrayList<String>();
eMinor.add("E");
eMinor.add("F#");
eMinor.add("G");
eMinor.add("A");
eMinor.add("B");
eMinor.add("C");
eMinor.add("D");
for (int numOFRandoStrings = 0; numOFRandoStrings < 10; numOFRandoStrings++) {
int[] randomList = Scramble(new Long(System.currentTimeMillis()).intValue() * numOFRandoStrings, 7); //numOFRandoStrings or any seed,7 means give me 7 random numbers from zero to 6
StringBuffer randomString = new StringBuffer();
for (int ind = 0; ind < randomList.length; ind++) {
randomString.append(eMinor.get(randomList[ind] ));
}
System.out.println("New Random String: " + randomString);
}
}
}
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);
}
}
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).