non static variable called from static content, java - java

I know this question was answered before, but I cant still handle it with my code.
Please can someone pointing out how can I fix it on this particular code. Id like to call trace(); but dont know where to call new trace. I tried different stuff from here but it does not work for me. Thank you!
package matr;
import java.util.Scanner;
final public class Matrix {
private final int M;
private final int N;
private double[][] data;
public Matrix(int M, int N) {
this.M = M;
this.N = N;
data = new double[M][N];
}
public Matrix(double[][] data) {
M = data.length;
N = data[0].length;
this.data = new double[M][N];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.data[i][j] = data[i][j];
}
private Matrix(Matrix A) {
this(A.data);
}
public static Matrix random(int M, int N, int r) {
Matrix A = new Matrix(M, N);
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
A.data[i][j] = (Math.random() * r);
}
}
return A;
}
public double trace() {
// trace a = new trace();
double t = 0;
for (int i = 0; i < Math.min(M, N); i++) {
t += data[i][i];
}
return t;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("rows: ");
try {
int x = Math.abs(scan.nextInt());
System.out.println("columns: ");
int y = Math.abs(scan.nextInt());
System.out
.println("generate: ");
int r = scan.nextInt();
Matrix A = Matrix.random(x, y, r);
System.out.println("random A");
trace();
} catch (java.util.InputMismatchException e) {
System.out.println("Please enter a valid int");
}
}
}

call A.trace()
use lower-case names for variables and fields
your main method is static. and your trace() method is a non-static method of the Matrix class. That means you have to call trace() on an instance of Matrix.

You are trying to call a non-static method trace() from a static method main(). Since 'main' is static it can only refer to static variables and static methods within the class. You will need to use an instance of Matrix to call trace. for example:
Matrix A = Matrix.random(x,y,r);
A.trace();

You need to call the trace() method on an instance of the type Matrix.
You could do this simply by:
A.trace();

Related

What's wrong with my constructor in this moving x matrix?

The idea is each iteration will move the [x] every time it prints. However it obviously can't print a 0x0 matrix. As you can see I summoned the constructor in the program to have the variables 4, 4. Yet for some reason, after running it, the program still outputs 0,0.
public class MovingX{
private int rowsN;
private int columnsM;
private int[][] matrixArr = new int[rowsN][columnsM];
private int x = 0;
private int y = 0;
public MovingX(int n, int m){
n = rowsN;
m = columnsM;
}
public void forLoopGrid(){
for(int i = 0; i < matrixArr.length; i++){
for(int j = 0; j < matrixArr.length; j++){
if(i == x && j == y) System.out.print("[x] ");
else System.out.print("[ ] ");
}
System.out.println();
}
System.out.println();
}
public void moveX(){
if(x < rowsN) x++;
else{
x = 0; y++;
}
}
public void runProgram(){
System.out.println("Program Starting");
System.out.println("Rows, Columns: " + rowsN + " " + columnsM);
for(int i = 0; i < (rowsN * columnsM); i++){
System.out.println("Stuff happening");
forLoopGrid();
moveX();
}
System.out.println("Program Ending");
}
public static void main(String[] args){
MovingX xLoop = new MovingX(4, 4);
xLoop.runProgram();
}
}
The problem seems to be the fact that you are assigning your object's fields(rowsN,columnsM) to the arguments(n,m) supplied to your class constructor.
You see, it doesn't matter what arguments you supply during instantiation when you use those local constructor variables to store the default value of your object's fields. You get (0,0) because all object fields get initialized to a default value and for int, that happens to be 0.
This should work--
public MovingX(int n, int m){
rowsN=n; //n = rowsN;
columnsM=m; //m = columnsM;
}
Reason maybe with the assignment.
public MovingX(int n, int m){
rowsN = n;
columnsM = m;
}
Try this, they may work.

Left Rotation using Java

Here I am Getting an ERROR
Cannot make a static reference to the non-static method leftRotatebyOne(int[], int) from the type LeftRotation
Here is my code..
public static int[] arrayLeftRotation(int[] arr, int n, int k)
{
int i;
for (i = 0; i < k; i++)
leftRotatebyOne(arr, n);
}
void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
for(int a_i=0; a_i < n; a_i++)
{
a[a_i] = in.nextInt();
}
int[] output = new int[n];
output = arrayLeftRotation(a, n, k);
for(int i = 0; i < n; i++)
System.out.print(output[i] + " ");
}
Can anybody tell to proceed me further.
In the main method you are calling arrayLeftRotation method (which is static) which in turn is calling leftRotatebyOne, here leftRotatebyOne is non-static method, which is being called through a static method which is not allowed in java.
Change the declaration of the method leftRotatebyOne to static as follows
static void leftRotatebyOne(int arr[], int n)

Program with threads for matrix multiplication

I'm trying to create a Java program with threads for matrix multiplication. This is the source code:
import java.util.Random;
public class MatrixTest {
//Creating the matrix
static int[][] mat = new int[3][3];
static int[][] mat2 = new int[3][3];
static int[][] result = new int[3][3];
public static void main(String[] args) {
//Creating the object of random class
Random rand = new Random();
//Filling first matrix with random values
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
mat[i][j] = rand.nextInt(10);
}
}
//Filling second matrix with random values
for (int i = 0; i < mat2.length; i++) {
for (int j = 0; j < mat2[i].length; j++) {
mat2[i][j] = rand.nextInt(10);
}
}
try {
//Object of multiply Class
Multiply multiply = new Multiply(3, 3);
//Threads
MatrixMultiplier thread1 = new MatrixMultiplier(multiply);
MatrixMultiplier thread2 = new MatrixMultiplier(multiply);
MatrixMultiplier thread3 = new MatrixMultiplier(multiply);
//Implementing threads
Thread th1 = new Thread(thread1);
Thread th2 = new Thread(thread2);
Thread th3 = new Thread(thread3);
//Starting threads
th1.start();
th2.start();
th3.start();
th1.join();
th2.join();
th3.join();
} catch (Exception e) {
e.printStackTrace();
}
//Printing the result
System.out.println("\n\nResult:");
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}//End main
}//End Class
//Multiply Class
class Multiply extends MatrixTest {
private int i;
private int j;
private int chance;
public Multiply(int i, int j) {
this.i = i;
this.j = j;
chance = 0;
}
//Matrix Multiplication Function
public synchronized void multiplyMatrix() {
int sum = 0;
int a = 0;
for (a = 0; a < i; a++) {
sum = 0;
for (int b = 0; b < j; b++) {
sum = sum + mat[chance][b] * mat2[b][a];
}
result[chance][a] = sum;
}
if (chance >= i)
return;
chance++;
}
}//End multiply class
//Thread Class
class MatrixMultiplier implements Runnable {
private final Multiply mul;
public MatrixMultiplier(Multiply mul) {
this.mul = mul;
}
#Override
public void run() {
mul.multiplyMatrix();
}
}
I just tried on Eclipse and it works, but now I want to create another version of that program in which, I use one thread for each cell that I'll have on the result matrix. For example I've got two 3x3 matrices. So the result matrix will be 3x3. Then, I want to use 9 threads to calculate each one of the 9 cells of the result matrix.
Can anyone help me?
You can create n Threads as follows (Note: numberOfThreads is the number of threads that you want to create. This will be the number of cells):
List<Thread> threads = new ArrayList<>(numberOfThreads);
for (int x = 0; x < numberOfThreads; x++) {
Thread t = new Thread(new MatrixMultiplier(multiply));
t.start();
threads.add(t);
}
for (Thread t : threads) {
t.join();
}
Please use the new Executor framework to create Threads, instead of manually doing the plumbing.
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreadsInPool);
for (int i = 0; i < numberOfThreads; i++) {
Runnable worker = new Thread(new MatrixMultiplier(multiply));;
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
With this code i think that i resolve my problem. I don't use synchronized in the methods but i think that is not necessary in that case.
import java.util.Scanner;
class MatrixProduct extends Thread {
private int[][] A;
private int[][] B;
private int[][] C;
private int rig, col;
private int dim;
public MatrixProduct(int[][] A, int[][] B, int[][] C, int rig, int col, int dim_com) {
this.A = A;
this.B = B;
this.C = C;
this.rig = rig;
this.col = col;
this.dim = dim_com;
}
public void run() {
for (int i = 0; i < dim; i++) {
C[rig][col] += A[rig][i] * B[i][col];
}
System.out.println("Thread " + rig + "," + col + " complete.");
}
}
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner In = new Scanner(System.in);
System.out.print("Row of Matrix A: ");
int rA = In.nextInt();
System.out.print("Column of Matrix A: ");
int cA = In.nextInt();
System.out.print("Row of Matrix B: ");
int rB = In.nextInt();
System.out.print("Column of Matrix B: ");
int cB = In.nextInt();
System.out.println();
if (cA != rB) {
System.out.println("We can't do the matrix product!");
System.exit(-1);
}
System.out.println("The matrix result from product will be " + rA + " x " + cB);
System.out.println();
int[][] A = new int[rA][cA];
int[][] B = new int[rB][cB];
int[][] C = new int[rA][cB];
MatrixProduct[][] thrd = new MatrixProduct[rA][cB];
System.out.println("Insert A:");
System.out.println();
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cA; j++) {
System.out.print(i + "," + j + " = ");
A[i][j] = In.nextInt();
}
}
System.out.println();
System.out.println("Insert B:");
System.out.println();
for (int i = 0; i < rB; i++) {
for (int j = 0; j < cB; j++) {
System.out.print(i + "," + j + " = ");
B[i][j] = In.nextInt();
}
}
System.out.println();
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cB; j++) {
thrd[i][j] = new MatrixProduct(A, B, C, i, j, cA);
thrd[i][j].start();
}
}
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cB; j++) {
try {
thrd[i][j].join();
} catch (InterruptedException e) {
}
}
}
System.out.println();
System.out.println("Result");
System.out.println();
for (int i = 0; i < rA; i++) {
for (int j = 0; j < cB; j++) {
System.out.print(C[i][j] + " ");
}
System.out.println();
}
}
}
Consider Matrix.java and Main.java as follows.
public class Matrix extends Thread {
private static int[][] a;
private static int[][] b;
private static int[][] c;
/* You might need other variables as well */
private int i;
private int j;
private int z1;
private int s;
private int k;
public Matrix(int[][] A, final int[][] B, final int[][] C, int i, int j, int z1) { // need to change this, might
// need some information
a = A;
b = B;
c = C;
this.i = i;
this.j = j;
this.z1 = z1; // a[0].length
}
public void run() {
synchronized (c) {
// 3. How to allocate work for each thread (recall it is the run function which
// all the threads execute)
// Here this code implements the allocated work for perticular thread
// Each element of the resulting matrix will generate by a perticular thread
for (s = 0, k = 0; k < z1; k++)
s += a[i][k] * b[k][j];
c[i][j] = s;
}
}
public static int[][] returnC() {
return c;
}
public static int[][] multiply(final int[][] a, final int[][] b) {
/*
* check if multipication can be done, if not return null allocate required
* memory return a * b
*/
final int x = a.length;
final int y = b[0].length;
final int z1 = a[0].length;
final int z2 = b.length;
if (z1 != z2) {
System.out.println("Cannnot multiply");
return null;
}
final int[][] c = new int[x][y];
int i, j;
// 1. How to use threads to parallelize the operation?
// Every element in the resulting matrix will be determined by a different
// thread
// 2. How may threads to use?
// x * y threads are used to generate the result.
for (i = 0; i < x; i++)
for (j = 0; j < y; j++) {
try {
Matrix temp_thread = new Matrix(a, b, c, i, j, z1);
temp_thread.start();
// 4. How to synchronize?
// synchronized() is used with join() to guarantee that the perticular thread
// will be accessed first
temp_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return Matrix.returnC();
}
}
You can use Main.java to give 2 matrices that need to be multiplied.
class Main {
public static int[][] a = {
{1, 1, 1},
{1, 1, 1},
{1, 1, 1}};
public static int[][] b = {
{1},
{1},
{1}};
public static void print_matrix(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++)
System.out.print(a[i][j] + " ");
System.out.println();
}
}
public static void main(String[] args) {
int[][] x = Matrix.multiply(a, b);
print_matrix(x); // see if the multipication is correct
}
}
In simple terms, what you all need to do is,
1) Create n (no of cells in resultant matrix) threads. Assign their roles. (Ex: Consider M X N, where M and N are matrices. 'thread1' is responsible for the multiplication of M's row_1 elements with N's column_1 elements and storing the result. This is the value for the resultant matrix's cell_1.)
2) Start each thread's process. (by start() method)
3) Wait until all the threads finish their processes and store the resultant value of each cell. Because those processes should be finished before displaying the resultant matrix. (You can do this by join() methods, and other possibilities too)
4) Now, you can display the resultant matrix.
Note:
1) Since, in this example, the shared resources (M and N) are only used to read only purpose, you don't need to use 'synchronized' methods to access them.
2) You can see, in this program, there are a group of threads running and all of them needs to achieve a specific status by their own, before continuing the next step of the whole program. This multi-threaded programming model is known as a Barrier.
Tried below code in eclipse as per thread for each cell. It works fine, you can check it.
class ResMatrix {
static int[][] arrres = new int[2][2];
}
class Matrix {
int[][] arr = new int[2][2];
void setV(int v) {
//int tmp = v;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
arr[i][j] = v;
v = v + 1;
}
}
}
int[][] getV() {
return arr;
}
}
class Mul extends Thread {
public int row;
public int col;
Matrix m;
Matrix m1;
Mul(int row, int col, Matrix m, Matrix m1) {
this.row = row;
this.col = col;
this.m = m;
this.m1 = m1;
}
public void run() {
//System.out.println("Started Thread: " + Thread.currentThread().getName());
int tmp = 0;
for (int i = 0; i < 2; i++) {
tmp = tmp + this.m.getV()[row][i] * this.m1.getV()[i][col];
}
ResMatrix.arrres[row][col] = tmp;
System.out.println("Started Thread END: " + Thread.currentThread().getName());
}
}
public class Test {
//static int[][] arrres =new int[2][2];
public static void main(String[] args) throws InterruptedException {
Matrix mm = new Matrix();
mm.setV(1);
Matrix mm1 = new Matrix();
mm1.setV(2);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Mul mul = new Mul(i, j, mm, mm1);
mul.start();
// mul.join();
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.println("VALUE: " + ResMatrix.arrres[i][j]);
}
}
}
}
In my solution I assigned to each worker a number of rows numRowForThread equals to: (number of rows of matA) / (number of threads).
public class MatMulConcur {
private final static int NUM_OF_THREAD = 1;
private static Mat matC;
public static Mat matmul(Mat matA, Mat matB) {
matC = new Mat(matA.getNRows(), matB.getNColumns());
return mul(matA, matB);
}
private static Mat mul(Mat matA, Mat matB) {
int numRowForThread;
int numRowA = matA.getNRows();
int startRow = 0;
Worker[] myWorker = new Worker[NUM_OF_THREAD];
for (int j = 0; j < NUM_OF_THREAD; j++) {
if (j < NUM_OF_THREAD - 1) {
numRowForThread = (numRowA / NUM_OF_THREAD);
} else {
numRowForThread = (numRowA / NUM_OF_THREAD) + (numRowA % NUM_OF_THREAD);
}
myWorker[j] = new Worker(startRow, startRow + numRowForThread, matA, matB);
myWorker[j].start();
startRow += numRowForThread;
}
for (Worker worker : myWorker) {
try {
worker.join();
} catch (InterruptedException e) {
}
}
return matC;
}
private static class Worker extends Thread {
private int startRow, stopRow;
private Mat matA, matB;
public Worker(int startRow, int stopRow, Mat matA, Mat matB) {
super();
this.startRow = startRow;
this.stopRow = stopRow;
this.matA = matA;
this.matB = matB;
}
#Override
public void run() {
for (int i = startRow; i < stopRow; i++) {
for (int j = 0; j < matB.getNColumns(); j++) {
double sum = 0;
for (int k = 0; k < matA.getNColumns(); k++) {
sum += matA.get(i, k) * matB.get(k, j);
}
matC.set(i, j, sum);
}
}
}
}
}
where for the class Mat, I used this implementation:
public class Mat {
private double[][] mat;
public Mat(int n, int m) {
mat = new double[n][m];
}
public void set(int i, int j, double v) {
mat[i][j] = v;
}
public double get(int i, int j) {
return mat[i][j];
}
public int getNRows() {
return mat.length;
}
public int getNColumns() {
return mat[0].length;
}
}

A method that calls an array and returns a different array is giving a can't resolve B to a variable error

I am calling one array and returning another array that is sorted based on the other array.
I think my method is proper but when I try to print out from the new array in the main method i'm getting an error that reads,
"Cannot resolve B to a variable."
B is the name of the new array that my method should return.
Thanks in advance.
package sort;
public class SortByFinal {
public static int [][] sortByFinal(int n, int [][] A)
{
int [][]B = new int [n][3];
int max = 0;
for(int i =0; i<n; i++)
{
for(int j = i; j<n; j++)
{
max = Math.max(A[i][1], max);
}
for(int k = i; k<n; k++)
{
if(A[k][1] == max)
{
B[k][0] = A[k][0];
B[k][1] = A[k][1];
B[k][2] = A[k][2];
}
}
}
return B;
}
public static void main(String []args)
{
int num = 5;
int[][] now = new int [num][3];
now[0][0] = 2342;
now[0][1] = 88;
now[0][2] = 98;
now[1][0] = 3901;
now[1][1] = 75;
now[1][2] = 71;
now[2][0] = 1444;
now[2][1] = 60;
now[2][2] = 85;
now[3][0] = 5327;
now[3][1] = 95;
now[3][2] = 80;
now[4][0] = 4888;
now[4][1] = 83;
now[4][2] = 100;
//int [][] B = new int[num][3];
sortByFinal(num, now);
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(B[i][j]);//this gives me the "B cannot be resolved to a variable."
System.out.print(" ");
}
System.out.println();
}
}
}
B is defined in sortByFinal(), but not in main(). To fix this, you could change your main to the follow:
int[][] B = sortByFinal(num, now);
Since sortByFinal(num, now) returns a int[][], this will work.
In your code, you're calling the function, but not doing anything with the return value, and you do not have access to the local variables of other methods; hence, the message.

method cannot be applied to given types

In my program, I'm trying to call the throwDice method in a different class.
public class SimpleDice {
private int diceCount;
public SimpleDice(int the_diceCount){
diceCount = the_diceCount;
}
public int tossDie(){
return (1 + (int)(Math.random()*6));
}
public int throwDice(int diceCount){
int score = 0;
for(int j = 0; j <= diceCount; j++){
score = (score + tossDie());
}
return score;
}
}
import java.util.*;
public class DiceTester {
public static void main(String[] args){
int diceCount;
int diceScore;
SimpleDice d = new SimpleDice(diceCount);
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of dice.");
diceCount = scan.nextInt();
System.out.println("Enter target value.");
diceScore = scan.nextInt();
int scoreCount = 0;
for(int i = 0; i < 100000; i++){
d.throwDice();
if(d.throwDice() == diceScore){
scoreCount += 1;
}
}
System.out.println("Your result is: " + (scoreCount/100000));
}
}
When I compile it, an error pops up for the d.throwdice() and says it can't be applied. It says it needs an int and there are no arguments. But I called an int diceCount in the throwDice method, so I don't know what's wrong.
for(int i = 0; i < 100000; i++){
d.throwDice();
if(d.throwDice() == diceScore){
scoreCount += 1;
}
}
There are two things wrong with this code:
It calls throwDice without an int (you have defined it as public int throwDice(int diceCount), so you must give it an int)
It calls throwDice twice each loop
You could fix it like this:
for(int i = 0; i < 100000; i++){
int diceResult = d.throwDice(diceCount); // call it with your "diceCount"
// variable
if(diceResult == diceScore){ // don't call "throwDice()" again here
scoreCount += 1;
}
}
You've defined throwDice as taking an int as follows:
public int throwDice(int diceCount)
But you are calling it without any args which just won't work:
d.throwDice();
throwDice() does require you to pass an int as the parameter:
public int throwDice(int diceCount){..}
And you are providing no arguments:
d.throwDice();
You need to pass an int as the parameter in order to make this work:
int n = 5;
d.throwDice(n);
The variable diceCount on the method declaration of throwDice(int diceCount) only indicates it requires an int as an argument and that the argument will be stored in the variable diceCount, it doesn't actually provide the actual primitive int.
Finally, you are also calling throwDice twice.

Categories

Resources