Error when Calling a Java Method - java

I am new to Java and am having an issue calling a method. I was hoping someone might be able to help me figure out what is going on.
The code I have is as follows:
public class QuickFindUF
{
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}
I took a look on Stack and figured the way to call my method would be using the following code: QuickFindUF x = new QuickFindUF(10);
When I run this I get an error that says
QuickFindUF.java:27: error: class, interface, or enum expected
QuickFindUF x = new QuickFindUF(10);
^
1 error
If someone could point me in the right direction I would really appreciate it. Thanks.

If the code you posted is your complete code, it appears you need a main method.
public class QuickFindUF
{
//
// add this so you can run code when your program executes
//
public static void main(String[] args)
{
QuickFindUF x = new QuickFindUF(10);
//
// call your methods on x here
// e.g.
// boolean connected = x.connected(2, 3);
//
}
private int[] id;
public QuickFindUF(int N)
{
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public boolean connected(int p, int q)
{ return id[p] == id[q]; }
public void union(int p, int q)
{
int pid = id[p];
int qid = id[q];
for (int i = 0; i < id.length; i++)
if (id[i] == pid) id[i] = qid;
}
}

Your main method might be outside the class , You need to declare main method inside the class like this way :
public static void main(String []args){
QuickFindUF x = new QuickFindUF(10);
}

Related

array in constructor keeps returning as null? [duplicate]

This question already has answers here:
Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
(4 answers)
Closed 3 months ago.
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
int[] pascal;
char[] Larray;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
im trying to do this code but pascal, keeps returning as null, when I declare it outside the constructor;
ive also tried this...
public class sierpinski {
public static void main(String[] args) {
sierpinski s1 = new sierpinski(3);
System.out.println(String.valueOf(s1.pascal));
}
int row;
String LString;
public static int fact( int n) {
int solution = 1;
if (n == 0) {
solution= 1;
return solution;
}
else {
for (int i = 2; i <= n; i++) {
solution = solution * i;
}
}
return solution;
}
public static int ncr( int n , int r){
int ncr1 = fact(n)/(fact(r) * fact(n-r));
return ncr1;
}
sierpinski( int row){
this.row = row;
char[] Larray = new char[row+1];
int[] pascal = new int[row+1];
for(int i =0; i < row+1; i++){
int a = ncr(row, i);
pascal[i] = a;
}
String LString = String.valueOf(Larray);
}
}
and I get this error
sierpinski.java:8: error: cannot find symbol
System.out.println(String.valueOf(s1.pascal));
^
symbol: variable pascal
location: variable s1 of type sierpinski
1 error
error: compilation failed
saying it cannot find symbol, any solutions and does anyone know how to fix this??
thanks
tried declaring the variable at the top, but I have no clue how to get this to work, any ideas?
Constructors are essentially methods.
sierpinski(int row) { // this is a constructor
this.row = row; // this sets a field.
int[] pascal = new int[row+1]; // this creates a new local variable
// constructor ends, and with it, all local variables GO AWAY
}
You want to declare a field. You already have one (row), and you already set it (this.row = row). If you want pascal to still exist when the constructor ends, it needs to be a field and not a local:
public Sierpinski {
private int row;
private int[] pascal;
public Sierpinski(int row) {
this.row = row;
this.pascal = new int[row];
}
}

Run Time Error on Java: "Null Pointer Exception" [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am getting this run time error which says there is a null pointer exception. I am just a beginner at Java and don't understand what this means.
Error message is as follows:
Exception in thread "main" java.lang.NullPointerException
at MyLongArray.insert(MyLongArray.java:26)
at MyLongArray.main(MyLongArray.java:69)
import java.util.*;
public class MyLongArray
{
private long a[];
private int nElems;
public MyLongArray(int size)
{
long[] a = new long[size];
nElems = a.length;
}
public int find(long searchKey) {
int m =0;
for(int i=0; i < nElems; i++)
if(searchKey == a[i])
m = i;
return m;
}
public void insert(long value) {
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.print("At what index do you want to insert? "); int i = sc.nextInt();
a[i] = value;
}
public long getElem(int index) {
return a[index];
}
public boolean delete(long value) {
long[] temp = new long[nElems];
int f = 0;
int o = 0;
for(int i=0; i < nElems; i++)
{
if(value != a[i])
{
temp[o++] = a[i];
}
else
f = 1;
}
for(int j=0; j < nElems; j++)
a[j] = temp[j];
for(int i=0; i < nElems; i++)
System.out.print(a[i] + " ");
if (f==1)
return true;
else
return false;
}
public void display()
{
for(int i =0; i < nElems; i++)
System.out.print(a[i] + " ");
}
public static void main(String[] args)
{
MyLongArray m = new MyLongArray(5);
m.insert(5);
m.find(21);
m.getElem(2);
m.delete(3);
m.display();
}
}
In constructor MyLongArray with long[] a = new long[size], you are declaring new local array a, instead of initializing your class variable array. After that in the insert method, you are trying to set elements in a non-initialized array a.
Use a = new long[size] instead of long[] a = new long[size].
You need to use a = new long[size] or this.a = new long[size] to initialize the instance field instead of declaring a local variable a inside the constructor.

How to initialize an array to avoid a Null Pointer Exception?

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.

Aid with quick sort algorithm in java (netbeans)

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.

Java Thread execution on same data

first of all here is the code, you can just copy an paste
import java.util.ArrayList;
public class RepetionCounter implements Runnable{
private int x;
private int y;
private int[][] matrix;
private int xCounter;
private int yCounter;
private ArrayList<Thread> threadArray;
private int rowIndex;
private boolean[] countCompleted;
public RepetionCounter(int x, int y, int [][]matrix)
{
this.x = x;
this.y = y;
this.matrix = matrix;
this.threadArray = new ArrayList<Thread>(matrix.length);
this.rowIndex = 0;
for(int i = 0; i < matrix.length; i++){
threadArray.add(new Thread(this));
}
countCompleted = new boolean[matrix.length];
}
public void start(){
for (int i = 0; i < threadArray.size(); i++){
threadArray.get(i).start();
this.rowIndex++;
}
}
public void count(int rowIndex)
{
for(int i = 0; i < matrix[rowIndex].length; i++){
if (matrix[rowIndex][i] == x){
this.xCounter++;
} else if (matrix[rowIndex][i] == y){
this.yCounter++;
}
}
}
#Override
public void run() {
count(this.rowIndex);
countCompleted[this.rowIndex] = true;
}
public int getxCounter() {
return xCounter;
}
public void setxCounter(int xCounter) {
this.xCounter = xCounter;
}
public int getyCounter() {
return yCounter;
}
public void setyCounter(int yCounter) {
this.yCounter = yCounter;
}
public boolean[] getCountCompleted() {
return countCompleted;
}
public void setCountCompleted(boolean[] countCompleted) {
this.countCompleted = countCompleted;
}
public static void main(String args[]){
int[][] matrix = {{0,2,1}, {2,3,4}, {3,2,0}};
RepetionCounter rc = new RepetionCounter(0, 2, matrix);
rc.start();
boolean ready = false;
while(!ready){
for(int i = 0; i < matrix.length; i++){
if (rc.getCountCompleted()[i]){
ready = true;
} else {
ready = false;
}
}
}
if (rc.getxCounter() > rc.getyCounter()){
System.out.println("Thre are more x than y");
} else {System.out.println("There are:"+rc.getxCounter()+" x and:"+rc.getyCounter()+" y");
}
}
}
What I want this code to do: I give to the object a matrix and tow numbers, and I want to know how much times these two numbers occurs in the matrix. I create as many thread as the number of rows of the matrix (that' why there is that ArrayList), so in this object I have k threads (supposing k is the number of rows), each of them count the occurrences of the two numbers.
The problem is: if I run it for the first time everything work, but if I try to execute it another time I get and IndexOutOfBoundException, or a bad count of the occurrences, the odd thing is that if I get the error, and modify the code, after that it will works again just for once.
Can you explain to me why is this happening?
You are using the same instance of RepetitionCounter for each thread:
for(int i = 0; i < matrix.length; i++){
threadArray.add(new Thread(this));
}
so they will all share the same rowIndex. The code is pretty confusing as it is, so I suggest you encapsulate the logic for the threads in a separate Runnable class with individual row ids:
class ThreadTask implements Runnable {
private int rowId;
private int[][] matrix;
public ThreadTask(int[][] matrix, int rowId) {
this.matrix = matrix; // only a reference is passed here so no worries
this.rowId = rowId;
}
public void run() {
// search on my row
}
}
then:
for(int i = 0; i < matrix.length; i++) {
threadArray.add(new Thread(new ThreadTask(matrix, i)));
}
You need to give each thread its own Runnable. Having them all share the same Runnable is going to cause disastrous race conditions. Separate out the logic each thread needs to do into a Runnable. Then move the part of the code that starts up the threads to a place outside the Runnable.
BTW look into Executors in the java.util.concurrent package, you don't have to use raw threads for this stuff. Also using Executors may give you a better idea about separating what goes into the Task from other stuff.

Categories

Resources