What is wrong with my code? I am trying to pass two arguments(one for random seed and another for the and i get the array our of bounds exception error.. I dont understand what i am doing wrong.. I appreciate any help
import java.util.Random;
public class sparse {
public static int size;
public static int matrix[][] = new int[size][size];
public static int seed;
public static void main(String args[]) {
seed = Integer.parseInt(args[0]);
size = Integer.parseInt(args[1]);
matrix = matrixGen();
}
public static int[][] matrixGen() {
Random r = new Random(seed);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = r.nextInt(100);
}
}
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(" " + matrix[i][j]);
}
System.out.println(" ");
}
return matrix;
}
}
You get the error because you allocate the matrix at the time when the size is still zero:
public static int matrix[][] = new int[size][size]; // size is zero here
You need to remove the initialization from the declaration, and move it to the main(), after reading the size from args.
public static void main(String args[]) {
seed = Integer.parseInt(args[0]);
size = Integer.parseInt(args[1]);
matrix = new int[size][size];
matrix = matrixGen();
}
You must initialize the size of the matrix before allocating the space for it:
public static int size = 30; // or whatever value do you want
The static fields seed and size have the default value (0) when you initialize the matrix field.
Thus matrix is a 0x0 array, without space for any element: any access will give such an exception.
To fix, you should set the matrix field in the main function, after arguments' parse.
Related
I need to make a Sum of the columns of a Matrice, but, I need to use a function or method. I can't make the sum on " public static void main(String[] args)".
I'm reading the values for the matrice, but I'm having troubles to send the values for and static method or a function?
How I can solve this problem?
public class QuadMagico {
static int sumcolumns (int S[N]){
return 0;
}
public static void main(String[] args) {
int N;
Scanner sc1 = new Scanner(System.in);
N = sc1.nextInt();
N++;
int D[][] = new int[N][N];
for (int i = 1; i < D.length; i++) {
for (int j = 1; j < D.length; j++) {
D[i][j] = sc1.nextInt();
}
}
All your code should be completely error free, except this line. static int sumcolumns (int S[N])
The solution? Remove the N in S[N]. It looks like this. static int sumcolumns (int S[]) Then, you are free to call the method whenever.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Having trouble understanding compile error. Main should be left unchanged. I believe MakeandFillMatix method is the problem and I can't figure it out. I think it's how I created the method.
import java.util.*;
/*
*/
public class TesterProject
{
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);
printMatrix(m);
}
public static int getMatrixSize()
{
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextint();
return n;
}
public static void makeAndFillMatrix(int [][] r)
{
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j]= rand;
}
}
return r;
}
public static void printMatrix(int [][] matrix)
{
for(int r = 0; r < matrix.length; r++)
{
for(int c = 0; c < matrix[r].length; c++)
{
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Hint
You have many problems in your code :
int n = S.nextint(); it should be int n = S.nextInt(); with Upper I
You can't compare an int with an array for (int j = 0; j < r; j++) { i think you need this for (int j = 0; j < i; j++) {
void makeAndFillMatrix(int[][] r) it not return any thing, and your return an array in the end.
makeAndFillMatrix(int[][] r) take an array of 2D and not an int int[][] m = makeAndFillMatrix(n);
Fix this problem and your problem is solve :)
EDIT
Then you have to change your code to be like this :
public static void main(String[] args) {
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);//<<<----Problem 4
printMatrix(m);
}
public static int getMatrixSize() {
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextInt();//<<--------------Problem 1
return n;
}
public static int[][] makeAndFillMatrix(int n) {//<<<---Problem 3
Random generator = new Random(5);
int[][] r = new int[n][n];
int rand = generator.nextInt(10);
for (int i = 0; i < r.length; i++) {
for (int j = 0; j < i; j++) {//<<<-----------Problem 2
r[i][j] = rand;
}
}
return r;
}
public static void printMatrix(int[][] matrix) {
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
Change makeAndFillMatrix(int[][] r) to makeAndFillMatrix(int r)
You want the matrix size, which is an integer, so take integer instead of a multidimensional array.
And in the for loop after that, change r.length to just r
Change void to int [][] in the method declaration.
In the method add a line int[][] q; and change r[i][j] = rand to q[i][j] = rand
And change return r to return q
The error you are receiving is due to you calling
int[][] m = makeAndFillMatrix(n);
in your main method.
You set n as an int in the line above, meaning n is a number, BUT, makeAndFillMatrix(int[][]) takes in a 2d array of ints. (A 2d array is a matrix, by the way.)
If you want to make a matrix of the size entered in by the user, then instead of passing n into your makeAndFillMatrix method, you would need to pass in a matrix of size n. You can do this in two ways. Option 1 is to pass in the matrix to your makeAndFillMatrix method like so:
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(new int[n][n]); // new int matrix of size n
printMatrix(m);
}
Or (the more conventional way, in my opinion), you can give makeAndFillMatrix the size of the matrix (like you are doing), and you can have makeAndFillMatrix make the array:
public static void makeAndFillMatrix(int matrixSize)
{
int[][] r = new int[matrixSize][matrixSize];
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r[i].length; j++) //~~~I modified this line as well~~~
{
r[i][j]= rand;
}
}
return r;
}
Anyways, you can take your pick at which approach you want to take to this problem, but regardless, I noticed that your makeAndFillMatrix method had an error. I fixed it and wrote //~~~I modified this line as well~~~
Your inner for loop originally said for(int j = 0; j < r; j++), but r is a matrix. For the inner loop, you would want to increase j until it has reached the size of the current row you are on in the matrix, so I changed that line as well. (Your inner loop was correct in your printMatrix method.) Whichever approach you take for your first issue, the inner loop in your makeAndFillMatrix method will need to be modified as well.
I hope this helps!
You are trying to cast 'int' (in the main function) to an 'int[][]' (the parameter of 'makeAndFillMatrix'. Also, makeAndFillMatrix returns 'void'.
I believe you want to rewrite your function to something like this:
public static int[][] makeAndFillMatrix(int r)
{
// Create a new matrix
int[][] matrix = new int[r][r];
// Get a random value
Random generator = new Random(5);
int rand = generator.nextInt(10);
// Assign random value to each cell of the matrix
for(int i = 0; i < r; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j] = rand;
}
}
// Return the matrix
return matrix;
}
I want to create a matrix in java .. I implemented the following code
public class Tester {
public static void main(String[] args) {
int[][] a = new int[2][0];
a[0][0] = 3;
a[1][0] = 5;
a[2][0] = 6;
int max = 1;
for (int x = 0; x < a.length; x++) {
for (int b = 0; b < a[x].length; b++) {
if (a[x][b] > max) {
max = a[x][b];
System.out.println(max);
}
System.out.println(a[x][b]);
}
}
System.out.println(a[x][b]);
}
}
When I run the code I get the following error :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at shapes.Tester.main(Tester.java:8)
I tried different methods to correct the code but nothing was helpful
Can you please correct the code for me ?
thank you
When you instantiate an array, you're giving it sizes, not indices. So to use the 0th index, you need at least a size of 1.
int[][] a = new int[3][1];
This will instantiate a 3x1 "matrix", meaning that valid indices for the first set of brackets are 0, 1 and 2; while the only valid index for the second set of brackets is 0. This looks like what your code requires.
public static void main(String[] args) {
// When instantiating an array, you give it sizes, not indices
int[][] arr = new int[3][1];
// These are all the valid index combinations for this array
arr[0][0] = 3;
arr[1][0] = 5;
arr[2][0] = 6;
int max = 1;
// To use these variables outside of the loop, you need to
// declare them outside the loop.
int x = 0;
int y = 0;
for (; x < arr.length; x++) {
for (; y < arr[x].length; y++) {
if (arr[x][y] > max) {
max = arr[x][y];
System.out.println(max);
}
System.out.println(arr[x][y]);
}
}
// This print statement accesses x and y outside the loop
System.out.println(arr[x][y]);
}
Your storing 3 elements in the first array.
try this int[][] a = new int[3][1];
I am relatively new to Java and for a school project I need to print a 2D array. The base for this project is to print it with values null. But I can't put this into a for loop without getting a java.lang.NullPointerException. Can anybody help?
private int ROWS;
private int COLUMNS;
private int WIDTH;
private String[][] sheet;
private String[][] values;
private int precision;
public SpreadSheet(int rows, int cols, int width, int precision) {
this.ROWS = rows;
this.COLUMNS = cols;
/*this.WIDTH = width;
this.precision = precision;*/
}
public void printSheet(){
for (int i = 0; i < sheet.length; i++) {
for (int j = 0; j < sheet[i].length; j++) {
System.out.println(sheet);
}
System.out.println("\n");
}
}
The main :
import java.util.Scanner;
public class DemoSpreadSheet {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
SpreadSheet sh = new SpreadSheet(4, 6, 15, 2);
sh.printSheet();
}
}
Make a small change to the SpreadSheet function:
public SpreadSheet(int rows;int cols;int width;int precision)
{
this.Sheet=new String[rows][cols];
/*creates an array with 4 rows and 6 columns..(assuming this is what you wanted to do)*/
}
There is also an error in your print sheet function:
System.out.println(Sheet); //illogical
/*sheet does not print the content of the array Sheet*/
Change this to:
System.out.println(Sheet[i][j]);
/*this will print null */
you need to initialisé your arrays.
sheet = new String[rows][cols]
This is an exemple you have other errors in you class.
This will do it (including better format):
public void printSheet(){
for (int i = 0; i < sheet.length; i++) {
for (int j = 0; j < sheet[i].length; j++) {
System.out.print(sheet[i][j] + " ");
}
System.out.println();
}
}
However, you have not assigned a length to your sheet. That means, at some point (at the constructor most likely) you have to define:
sheet = new String[rows][cols];
I am trying to concatenate two two-dimensional arrays of different sizes. I have no idea why my method doesn't work. Java tells me, when I mouse over the "return xx": "Type mismatch: cannot convert from int[][] to int[]". When I mouse over "concatenateArr2d..." I get: "Illegal modifier for parameter concatenateArr2d: only final is permitted".
I don't understand why I am getting this error.
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int[][] xx = new int[t.length + s.length][];
for(i = 0; i < xx.length; i++)
{
xx[i] = new int[t[i].length + s[i].length];
}
return xx;
}
I still have to do the code to fill the entries but that should not be a problem.
Any help please? Thank you.
It looks to me that the code before the bit you pasted does not have aligned braces. You're probably inside a method when you try to declare this method.
public class HelloWorld{
public static int[][] concatenateArr2d(int[][] t, int[][] s)
{
int jLength=0;
// The below line of code is to determine second dimension size of new array
jLength=Math.max(s[0].length, t[0].length);
int sIterate=0;
//new array created using size of first+second array for First dimension and maximum size for second dimension
int[][] xx = new int[t.length + s.length][jLength];
//first array copy
for(int i = 0; i < t.length; i++)
{
for(int j = 0; j < t[0].length; j++)
{
xx[i][j] =t[i][j];
}
}
//second array copy
for(int i = t.length; i < xx.length; i++)
{
for(int j = 0; j < s[0].length; j++)
{
xx[i][j] =s[sIterate][j];
}
sIterate++;
}
return xx;
}
public static void main(String []args){
int a[][]={{1,2},{2,3},{1,1}};
int b[][]={{1,2,3},{2,3,4}};
int c[][]=HelloWorld.concatenateArr2d(a,b);
//Output iteration
for(int i = 0; i < c.length; i++)
{
for(int j = 0; j < c[0].length; j++)
{
System.out.print(c[i][j]);
}
System.out.println();
}
}
}
note : The blanks filled by 'primitive type default value' like, for int its 0.
Output :
120
230
110
123
234