My code is returning Runtime error, but I don't Know how to fix this. This code is about the problem 104. I tried to change somethings but nothing... I read about this error and basically is associated with the Scanner.
Please Help me!
import java.util.Scanner;
public class Main {
static int MAX = 20;
static double LUCRO_MIN = 1.01;
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int n, i, j;
double v;
while(sc.hasNext()) {
double[][] W = new double [MAX][MAX];
n = sc.nextInt();
sc.nextLine();
for(i = 0; i < n; i++) {
int pos = 0;
String linha = sc.nextLine();
String vertice[] = linha.split(" ");
for(j = 0; j < n; j++) {
if(i == j) {
W[i][i] = 0;
continue;
}
v = Double.parseDouble(vertice[pos]);
W[i][j] = v;
pos++;
}
}
Converte(n, W);
}
}
static public void Imprime (int i, int j, int l, int P[][][]) {
if(l == 0)
System.out.printf ("%d\n", i + 1);
else {
System.out.printf ("%d ", i + 1);
Imprime (P[l][i][j], j, l - 1, P);
}
}
static void IniZero (int n, double m[][][], int l) {
int i, j;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
m[l][i][j] = 0;
}
static void Converte(int n, double W[][]) {
double[][][] B = new double [MAX][MAX][MAX];
int [][][]P = new int [MAX][MAX][MAX];
int l, i, j, k;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++) {
B[1][i][j] = W[i][j];
if(W[i][j] > 0)
P[1][i][j] = j;
}
for(l = 2; l <= n; l++) {
IniZero(n, B, l);
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
for(k = 0; k < n; k++) {
if(B[l][i][j] < W[i][k] * B[l - 1][k][j]) {
B[l][i][j] = W[i][k] * B[l - 1][k][j];
P[l][i][j] = k;
if(B[l][i][i] >= LUCRO_MIN) {
Imprime(i, i, l, P);
return;
}
}
}
}
System.out.printf("no arbitrage sequence exists\n");
}
}
Change scanner like this
Scanner input = new Scanner(System.in);
TO
Scanner input = new Scanner(new FileInputStream(args[0]));
and i recommad you to use input.hasNext() instead of input.nextInt();this can cause nullpointerexception
Related
The problem is when you entry an input with scanner ,it shows on console. I want them to shown in an order. I want them shown like a matris. But with nextInt method all shows bottom of each other.
I want a console output like this:
But with nextInt() method your new int shows on nextLine like this:
How can i show multiple variables in same line with scanner?
import java.util.Scanner;
public class ProbilityMatrixTest {
static int M;
static int N;
static float[][] matrixX;
static float[][] matrixY;
static boolean isProbilityMatrix;
public static void main(String[] args) {
initiate();
testMatrix(matrixX);
System.out.println();
multiplyMatrix();
testMatrix(matrixY);
}
public static void initiate() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row and column size of matrix : ");
M = sc.nextInt();
N = sc.nextInt();
System.out.println();
matrixX = new float[M][N];
System.out.println("Enter values of " + M + "x" + N + " matrix :");
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
matrixX[i][j] = sc.nextFloat();
}
}
}
public static void testMatrix(float[][] givenMatrix) {
isProbilityMatrix = true;
if (M != N) {
isProbilityMatrix = false;
}
for (int j = 0; j < N; j++) {
float rowVariablesTotal = 0;
for (int i = 0; i < M; i++) {
rowVariablesTotal += givenMatrix[i][j];
if (givenMatrix[i][j] < 0) {
isProbilityMatrix = false;
}
}
if (rowVariablesTotal != 1.0f) {
isProbilityMatrix = false;
}
}
System.out.print("TEST RESULT : ");
if (isProbilityMatrix) {
System.out.println("Probility matrix");
} else {
System.out.println("not Probility matrix");
}
}
public static void multiplyMatrix() {
matrixY = new float[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float newMatrixVariable = 0;
for (int a = 0; a < M; a++) {
newMatrixVariable += (matrixX[i][a] * matrixX[a][j]);
}
matrixY[i][j] = newMatrixVariable;
}
}
System.out.println("The square of given matrix:");
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
System.out.print(matrixY[i][j] + " ");
}
System.out.println();
}
}
}
You need to scan entire lines at a time. Otherwise, you're always pressing the enter key, causing it to look like you're entering one value before the other on previous lines
For example, type 3 3, then enter, then you can type three space separated decimal values, enter, then repeat that twice
System.out.print("Enter the row and column size of matrix : ");
String[] mn = sc.nextLine().split("\\s+");
int M = Integer.parseInt(mn[0]);
int N = Integer.parseInt(mn[1]);
System.out.println();
double[][] matrixX = new double[N][];
for (int i = 0; i < N; i++) {
matrixX[i] = new double[M];
String[] row = sc.nextLine().split("\\s+");
for (int j = 0: j < M: j++) {
matrix[i][j] = Double.parseDouble(row[j]);
//...
}
}
I feel like I'm really close with this implementation of a memoized matrix chain algorithm in Java, but I'm getting an array out of bounds error on line 45 and 53. These, for some reason, really seem to mess me up. Maybe there's something I'm continually messing up with, but I dunno, obviously. Can anyone help me out?
public class Lab2 {
//fields
static int p[];
static int m[][];
final static int INFINITY = 999999999;
public Lab2() {
//
}
public static void main(String[] args) {
Lab2 lab2 = new Lab2();
Lab2.m = new int[7][7];
Lab2.p = new int[7];
Lab2.p[0] = 20;
Lab2.p[1] = 8;
Lab2.p[2] = 4;
Lab2.p[3] = 25;
Lab2.p[4] = 30;
Lab2.p[5] = 5;
Lab2.p[6] = 10;
int n = Lab2.p.length-1;
//initialize m array to infinity
for (int i = 1; i <= n; i++){
for (int j = i; j <= n; j++){
Lab2.m[i][j]= INFINITY;
}
}
lab2.lookUpChain(m, p, 1, n);
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
System.out.println(m[i][j]);
}
}
}
//
public int lookUpChain(int m[][], int p[], int i, int j ){
if (m[i][j]<INFINITY){
return m[i][j];
}
if (i == j){
m[i][j] = 0;
}
else{
for (int k = i; k <= j; i++){
int q = (lookUpChain(m,p,i,k)) + (lookUpChain(m,p,k+1,j)) + (p[i]*p[k]*p[j]);
if (q < m[i][j]){
m[i][j] = q;
}
}
}
return m[i][j];
}
}
else{
for (int k = i; k <= j; i++)
Change to:
else{
for (int k = i; k <= j; k++) // change i to k
import java.util.*;
public class Algorithm {
public class Matrix{
private Double[][] x;
}
public static Scanner scan = new Scanner(System.in);
private static String str;
public static void read_data(Double[] degrees, Double[] l) {
l[0] = 0.0;
int i;
for (i = 0; i < 9; i++) {
str = scan.next(); //passem la primera columna
str = scan.next(); //agafem el valor del desplaçament
str = str.substring(0, str.length()-1); //traiem la coma
l[i+1] = Double.parseDouble(str);
str = scan.next(); //passem la primera columna
str = scan.next(); //agafem el valor del desplaçament
str = str.substring(0, str.length()-1); //traiem la coma
degrees[i] = Double.parseDouble(str);
}
degrees[i] = 0.0;
}
public static void init_Matrix(Double[][] M, int i, Double[] degrees, Double[] l) {
M[0][3] = l[i];
M[0][0] = Math.cos(degrees[i]);
M[0][1] = -Math.sin(degrees[i]);
M[1][0] = Math.sin(degrees[i]);
M[1][1] = Math.cos(degrees[i]);
for (int k = 0; i < 4; k++) {
for (int j = 0; j < 4; j++) {
if (k == j && (M[k][j] == null)) M[k][j] = 1.0;
else if(M[k][j] == null) M[k][j] = 0.0;
}
}
}
public static void init_Ultima_Matrix(Double[][] M, int i, Double[] l) {
M[0][3] = l[i];
for (int k = 0; k < 4; k++) {
for (int j = 0; j < 4; j++) {
if (k == j) M[k][j] = 1.0;
else if(M[k][j] == null) M[k][j] = 0.0;
}
}
}
public static void init_Derivada(Double[][] M, int i, Double[] degrees) {
M[0][0] = -Math.sin(degrees[i]);
M[0][1] = -Math.cos(degrees[i]);
M[1][0] = Math.cos(degrees[i]);
M[1][1] = -Math.sin(degrees[i]);
for (int k = 0; k < 4; k++) {
for (int j = 0; j < 4; j++) {
if(M[k][j] == null) M[k][j] = 0.0;
}
}
}
public static void init_Ultima_Derivada(Double[][] M, int i) {
for (int k = 0; k < 4; k++) {
for (int j = 0; j < 4; j++) {
M[k][j] = 0.0;
}
}
}
public static void fulfill_Ts(Matrix[] Ts, Double[] degrees, Double[] l) {
int i;
for (i = 0; i < 9; i++) {
Ts[i].x = new Double[4][4];
init_Matrix(Ts[i].x, i, degrees, l);
}
init_Ultima_Matrix(Ts[i].x, i, l);
}
public static void fulfill_Ds(Matrix[] Ds, Double[] degrees) {
int i;
for (i = 0; i < 9; i++) {
Ds[i].x = new Double[4][4];
init_Derivada(Ds[i].x, i, degrees);
}
init_Ultima_Derivada(Ds[i].x, i);
}
private static Double[][] product(Double[][] A, Double[][] B){
Double suma = 0.0;
Double result[][] = new Double[4][4];
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
suma = 0.0;
for(int k = 0; k < 4; k++){
suma += A[i][k] * B[k][j];
}
result[i][j] = suma;
}
}
return result;
}
private static void calc_Jacobian(Matrix[] Ts, Matrix[] Ds, int i, Double[][] jacobian) {
Double[][] tmp;
if (i == 0) tmp = Ds[0].x;
else tmp = Ts[0].x;
for (int j = 1; j < 10; j++) {
if (j == i) tmp = product(tmp, Ds[j].x);
else tmp = product(tmp, Ts[j].x);
}
jacobian[0][i] = tmp[0][3];
jacobian[1][i] = tmp[1][3];
jacobian[2][i] = tmp[0][0];
}
public static void main(String[] args) {
Matrix[] Ts = new Matrix[10];
Matrix[] Ds = new Matrix[10];
for (int i = 0; i < 10; i++) {
Ts[i].x = new Double[4][4];
Ds[i].x = new Double[4][4];
}
Double[] degrees = new Double[10];
Double[] l = new Double[10];
read_data(degrees, l);
fulfill_Ts(Ts, degrees, l);
fulfill_Ds(Ds, degrees);
Matrix jacobian = new Matrix();
jacobian.x = new Double[3][9];
for (int j=0; j<9; j++)
calc_Jacobian(Ts, Ds, j, jacobian.x);
//La matriu Jacobiana hauria d'estar acabada
}
}
Well, this is my code. The error is in the first line where says "Matrix jacobian = new Matrix();". Have I declared it wrong? The definition of Matrix is at the beginning of the code.
It says: No enclosing instance of type Algorithm is accessible. Must qualify the allocation with an enclosing instance of type Algorithm (e.g. x.new A() where x is an instance of Algorithm).
Moreover, I get an Exception with this: "Matrix[] Ts = new Matrix[10];". Can't I declare an array of elements Matrix?
Thank you very much.
Yes, try this: Matrix M = new Matrix();
This one Matrix[] Ts = new Matrix[10]; is valid but you should also loop through the array elements and initialize them by calling the constructor. Otherwise, they will remain having null values.
Change
public class Matrix
to
public static class Matrix
Creating a nested class without the static modifier creates a closure, which allows you to reference non-static members of the enclosing instance. If you don't declare it static, you need an enclosing instance (ie, a this) to create it, which you don't have in static void main().
Explaining a closure is beyond the scope of this answer, but it would be a private member Algorithm _closure in Matrix, which is implicitly referenced (the same way this is), when you mention a non-static member of Algorithm.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi I have the Jama librarry, but this libraray work only with Double numbers..and its very slow. for Android app ..and finally i dont need so high precision of eig decomp..so is there some JAva libaray with float num.....similar in syntax with jama? becouse...I dont want to re-- write again my 440 rows code thanks. eig. Transpose, inverse and so basic Linear algebra operations..
or exist same java library eigenvalues. with threads?
I know of one library called la4j, you might be interested in looking into that. I should mention that, generally, I don't think Java is a good choice if you're planning on doing many matrix manipulations/calculations (I myself have tried and hit a dead-end), you might be better off looking into Python (NumPy) or C++ (Armadillo) for such projects.
Or are you looking for something like this?
import java.util.Arrays;
public class Matrix {
protected int rows;
protected int cols;
double[][] values;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
values = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = 0;
}
public Matrix(int[][] M) {
this.rows = M.length;
this.cols = M[0].length;
values = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = M[i][j];
}
public Matrix(double[][] M) {
this.rows = M.length;
this.cols = M[0].length;
values = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = M[i][j];
}
public void setToEye() {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = (i == j) ? 1 : 0;
}
public static int[] matrixSize(Matrix M) {
int[] size = new int[2];
size[0] = M.rows;
size[1] = M.cols;
return size;
}
public static double vectMul(double[] A, double[] B) {
double suma = 0;
for (int i = 0; i < A.length; i++)
suma += A[i] * B[i];
return suma;
}
public static Matrix matrixTranspose(Matrix M) {
int[] size = matrixSize(M);
double[][] Mt = new double[size[0]][size[1]];
for (int i = 0; i < size[0]; i++)
for (int j = 0; j < size[1]; j++)
Mt[i][j] = M.getValue(j, i);
return new Matrix(Mt);
}
public static Matrix matrixMul(Matrix A, Matrix B) {
int m1 = matrixSize(A)[0];
int n1 = matrixSize(A)[1];
int m2 = matrixSize(B)[0];
int n2 = matrixSize(B)[1];
double[][] rez;
if (n1 != m2) {
System.err.println("Inner matrix dimensions must agree!");
return null;
}
rez = new double[m1][n2];
for (int i = 0; i < m1; i++)
for (int j = 0; j < n2; j++)
rez[i][j] = vectMul(A.getRow(i), B.getColumn(j));
Matrix r = new Matrix(rez);
return r;
}
public static Matrix matrixMulWithMod(Matrix A, Matrix B, double mod) {
int m1 = matrixSize(A)[0];
int n1 = matrixSize(A)[1];
int m2 = matrixSize(B)[0];
int n2 = matrixSize(B)[1];
double[][] rez;
if (n1 != m2) {
System.err.println("Inner matrix dimensions must agree!");
return null;
}
rez = new double[m1][n2];
for (int i = 0; i < m1; i++)
for (int j = 0; j < n2; j++)
rez[i][j] = vectMul(A.getRow(i), B.getColumn(j)) % mod;
Matrix r = new Matrix(rez);
return r;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.rows; i++) {
sb.append(Arrays.toString(values[i]));
sb.append('\n');
}
String str = sb.toString();
return str;
}
public double[][] getValues() {
return values;
}
public void setValues(double[][] values) {
this.values = values;
}
public void setValues(int[][] values) {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
this.values[i][j] = (double) values[i][j];
}
public double getValue(int row, int col) {
return values[row][col];
}
public void setValue(int row, int col, double value) {
values[row][col] = value;
}
public double[] getRow(int row) {
double[] temp = new double[cols];
for (int i = 0; i < temp.length; i++)
temp[i] = values[row][i];
return temp;
}
public double[] getColumn(int col) {
double[] temp = new double[rows];
for (int i = 0; i < temp.length; i++)
temp[i] = values[i][col];
return temp;
}
public double[] toDoubleArray() {
double[] temp = new double[rows * cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp[i * (rows + 1) + j] = values[i][j];
return temp;
}
public int[] toIntArray() {
int[] temp = new int[rows * cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp[i * (rows + 1) + j] = (int) values[i][j];
return temp;
}
public int getRowCount() {
return this.rows;
}
public int getColumnsCount() {
return this.cols;
}
public static double getMatrixDet(Matrix M) {
int m = M.getRowCount();
int n = M.getColumnsCount();
double D = 0;
if (m != n) {
System.err.println("Matrix must be square!");
System.exit(0);
}
if (n > 1) {
Matrix I = new Matrix(m - 1, n - 1);
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
I.setValue(i - 1, j - 1, M.getValue(i, j));
D = M.getValue(0, 0) * getMatrixDet(I);
} else
D = M.getValue(0, 0);
// za niz , kopira iz niza a elemente 0:i-1 i+1:n sredi za matrcu
Matrix I = new Matrix(m - 1, n - 1);
for (int i = 1; i < n; i++) {
I = M.withoutIthRowAndJthCol(i, 0);
D = D + Math.pow((-1), i) * M.getValue(i, 0) * getMatrixDet(I);
}
return D;
}
public Matrix transpose() {
Matrix temp = new Matrix(this.values);
for (int i = 0; i < this.rows; i++)
for (int j = 0; j < this.cols; j++)
this.values[i][j] = temp.getValue(j, i);
return this;
}
private Matrix withoutIthRowAndJthCol(int row, int col) {
Matrix temp = new Matrix(this.rows - 1, this.cols - 1);
int k = 0, l = 0;
for (int i = 0; i < this.getRowCount(); i++) {
if (i == row)
continue;
for (int j = 0; j < this.getColumnsCount(); j++) {
if (j == col)
continue;
temp.setValue(k, l, this.values[i][j]);
l++;
}
l %= 2;
k++;
}
return temp;
}
public static Matrix getMatrixAdj(Matrix M) {
int m = M.getRowCount();
int n = M.getColumnsCount();
Matrix A = new Matrix(m, n);
if (m != n) {
System.err.println("Matrix must be square!");
System.exit(0);
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
A.setValue(i, j, Math.pow((-1), i + j)
* getMatrixDet(M.withoutIthRowAndJthCol(i, j)));
}
A.transpose();
return A;
}
public static Matrix matrixDiv(Matrix M, double n) {
Matrix temp = M;
for (int i = 0; i < M.getRowCount(); i++)
for (int j = 0; j < M.getColumnsCount(); j++)
temp.setValue(i, j, (M.getValue(i, j) / n));
return temp;
}
public static Matrix getMatrixInv(Matrix M) {
Matrix I = new Matrix(M.getRowCount(), M.getColumnsCount());
if (M.getRowCount() != M.getColumnsCount()) {
System.err.println("Matrix must be square!");
System.exit(0);
}
if (getMatrixDet(M) == 0) {
System.err.println("Matrix is singular!");
System.exit(0);
}
I = matrixDiv(getMatrixAdj(M), getMatrixDet(M));
return I;
}
}
if this is what you wanted, you're welcome.
I am trying to run my code so it prints cyclic permutations, though I can only get it to do the first one at the moment. It runs correctly up to the point which I have marked but I can't see what is going wrong. I think it has no break in the while loop, but I'm not sure. Really could do with some help here.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPemutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPemutation(int p[])// (b)
{
System.out
.println("The permutation is represented by the cyclic notation:");
int[] B = new int[p.length];
int m = 0;
while (m < p.length)// this is the point at which my code screws up
{
if (!check(B, m)) {
B = parenthesis(p, m);
printParenthesis(B);
m++;
} else
m++;
}// if not there are then repeat
}
static int[] parenthesis(int p[], int i) {
int[] B = new int[p.length];
for (int a = p[i], j = 0; a != B[0]; a = p[a - 1], j++) {
B[j] = a;
}
return B;
}
static void printParenthesis(int B[]) {
System.out.print("( ");
for (int i = 0; i < B.length && B[i] != 0; i++)
System.out.print(B[i] + " ");
System.out.print(")");
}
static boolean check(int B[], int m) {
int i = 0;
boolean a = false;
while (i < B.length || !a) {
if ((ispresent(m, B, i))){
a = true;
break;
}
else
i++;
}
return a;
}
static boolean ispresent(int m, int B[], int i) {
return m == B[i] && m < B.length;
}
}
Among others you should check p[m] in check(B, p[m]) instead of m:
in static void printPemutation(int p[]):
while (m < p.length){
if (!check(B, p[m])) {
B = parenthesis(p, m);
printParenthesis(B);
}
m++;
}
then
static boolean check(int B[], int m) {
int i = 0;
while (i < B.length) {
if (m == B[i]) {
return true;
}
i++;
}
return false;
}
this does somehow more what you want, but not always i fear...