Help me with this Java code - java

Question:
matrix m1 = new matrix(); // should produce a matrix of 3*3
matrix m2 = new matrix(5,4); //5*4
matrix m3 = new matrix(m2); //5*4
What should be there in the copy constructor to make a new matrix m3 of the same order as of m2?
public class matrix {
int a[ ][ ];
matrix(){
a = new int[3][3];
}
matrix(int x, int y){
a= new int [x][y];
}
matrix (matrix b1){
//how to use value of x and y here....
}
void show(){
System.out.println(a.length);
for(int i=0;i<a.length;i++){
System.out.print(a[i].length);
}
}
}
public class matrixtest {
public static void main(String [ ] args){
matrix a = new matrix();
matrix b = new matrix(5,4);
matrix c = new matrix (b);
a.show();
b.show();
c.show();
}
}
NOTE: You can not use any extra instance variable except the array a.
Accepted answer: #Chankey: this(b1.a.length,b1.a[0].length); – John

Store the number of rows, and the number of columns in the matrix class, and create getters for them.
public class Matrix {
int[][] a;
int rowNum;
int colNum;
//...
public Matrix(Matrix b) {
a=new int[b.getRowNum()][b.getColNum()];
this.rowNum = b.getRowNum();
this.colNum = b.getColNum();
}
public int getRowNum() {
return this.rowNum;
}
}

You need to get the size of the passed b1 matrix
int x = b1.length;
int y = b1[0].lenght;
and can then use it to construct the final array.
a= new int [x][y];

Use
a =new int[b1.a.length][b1.a[0].length];
But it is not recommended .
you should have some get method , which return
matrix dimension.

This is homework, so I'll give you a hint:
How would you get the lengths of the 2 dimensional matrix (a[][]) of b1? proper methods in the matrix class will help - how would you implement those (getX, getY)?
Also, it is better to redirect the constructors to the most detailed one, for example:
matrix(){
this(3,3); // call the constructor below with parameters 3,3
}
matrix(int x, int y){
a= new int [x][y];
}

This can be the most probable answer without using any other instance variable other then the array itself:
import java.io.*;
class matrix
{
private int arr[][];
public matrix() //Default Constructor
{
this(3,3);
}
public matrix(int r,int c) //Parameterized Constructor
{
arr=new int[r][c];
read();
}
public matrix(matrix m) //Copy Constructor
{
System.out.println("Fetching array...");
int r,c;
r=m.arr.length;
c=m.arr[0].length;
arr=new int [r][c];
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
arr[i][j]=m.arr[i][j];
}
}
}
public void read()
{
int i,j,r,c;
r=arr.length;
c=arr[0].length;
Console con=System.console();
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
arr[i][j]=Integer.parseInt(con.readLine());
}
}
}
public void show()
{
int i,j;
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr[0].length;j++)
{
System.out.print(" "+arr[i][j]);
}
System.out.println();
}
}
}

Related

How can I export matrix from user input to other class as a two-dimensional array?

So I wrote a method to make a matrix from user input like this:
public class matrix1 {
public static void getMatrix() {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number of matrix rows. ");
int matrixRow;
do {
System.out.println("Please enter valid number.");
matrixRow = scan.nextInt() ;
} while (matrixRow>4);
System.out.println("Please enter the number of matrix columns.");
int matrixCol;
do {
System.out.println("Please enter valid number.");
matrixCol = scan.nextInt() ;
} while (matrixCol>4);
//defining 2D array to hold matrix data
int[][] matrix1 = new int[matrixRow][matrixCol];
enterMatrixData(scan, matrix1, matrixRow, matrixCol);
// Print Matrix Data
printMatrix(matrix1, matrixRow, matrixCol);
}
public static void enterMatrixData(Scanner scan, int[][] matrix, int matrixRow, int matrixCol){
System.out.println("Please enter data for your matrix.");
for (int i = 0; i < matrixRow; i++)
{
for (int j = 0; j < matrixCol; j++)
{
matrix[i][j] = scan.nextInt();
}
}
}
public static void printMatrix(int[][] matrix, int matrixRow, int matrixCol){
System.out.println("Your matrix is : ");
for (int i = 0; i < matrixRow; i++)
{
for (int j = 0; j < matrixCol; j++)
{
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
}
And it works like a charm, but I'm a total beginner and now I want to use this created array to multiply it by a scalar. In my main method I invoke
matrix1.getMatrix();
The multiplying method is in another class. Can I import this user-made array and use it in multiplying class?
Just change the return type to int[][] and add a return statement in the last line:
public int[][] getMatrix() {
// ... you already got all this
return matrix1;
}
Your main can then just call that:
public static void main(String[] args) {
int[][] matrix = getMatrix();
// now you can just pass it to your multiplier as a parameter, e.g.:
MatrixMultiplier.multiplyWithScalar(matrix, 2);
}
I would rename your getMatrix to something like readMatrix though, because there is a convention that methods named get[SomeFieldName] should be simple accessor functions that usually don't do a lot of work.
Better design, however, would be to wrap your primitive array as a member of your matrix class:
class Matrix {
private final int[][] data;
private Matrix(int[][] data) {
this.data = data;
}
public static Matrix fromUserInput() {
int[][] matrix1;
// code for reading from input here
return new Matrix(matrix1);
}
}
and make your Multiplier accept an instance of your Matrix class:
public static void main(String[] args) {
Matrix matrix = Matrix.fromUserInput();
MatrixMultiplier.multiplyWithScalar(matrix, 2);
}
Of course, now your matrix class needs to provide methods for getting and setting field values at specific indices.

Method in Java for creating an array with arbitrary number of dimensions

Is it possible in Java to create a method that return an array with the number of dimensions passed by parameter?
Here is the code I have so far:
public static Object buildMultiDimensionalArray(int numDimensions) {
if (numDimensions==1) {
return new int[1];
}
if (numDimensions==2) {
return new int[2][2];
}
if (numDimensions==3) {
return new int[3][3][3];
}
if (numDimensions==4) {
return new int[4][4][4][4];
}
if (numDimensions==5) {
return new int[5][5][5][5][5];
}
if (numDimensions==6) {
return new int[6][6][6][6][6][6];
}
// and so on...
return null;
}
But this works only for dimensions up to 6.
Is it possible to make this method work for any number of dimensions?
import java.lang.reflect.*;
import java.util.*;
public static Object nArray(int n) {
int[]dim = new int [n];
Arrays.fill(dim, n);
return Array.newInstance(int.class,dim);
}
Such many-dimension array is rarely seen in code. Maybe you could try one dimension array with the tuple(d1, d2 ...) mapped to the 1-d array index, the same power. for example, to visit the 2-nd row and 3-rd column of a[6][8], mapped to (2 * 8 + 3) 1-d array a[48]
You could return a single-dimension array with an explicit capacity and parse it as if it were a multidimensional array.
#SuppressWarnings("unchecked")
public static <T> T[] buildMultiDimensionalArray(int dimensions, Class<T> clazz) {
return (T[]) Array.newInstance(clazz, dimensions * dimensions);
}
class nArray {
int[] dims;
int[] mults;
int[] vals;
nArray(int ... d) {
int sum = 1;
int len = d.length;
dims = new int[len];
mults = new int[len];
for (int i=len-1; i>=0; i--) {
dims[i]=d[i];
mults[i] = sum;
sum*=d[i];
}
vals = new int[sum];
}
void set(int v, int ... d) {
int index = 0;
for (int i=0; i<d.length; i++) {
//if(d[i]>=dim[i]){throw new IndexOutOfBoundsException(); / NullPointerException } ???
index+=d[i]*mults[i];
}
vals[index] = v;
}
int get(int ... d) {
int index = 0;
for (int i=0; i<d.length; i++) {
// throw exception ?
index+=d[i]*mults[i];
}
return vals[index];
}
}
https://pastebin.com/k0hqcu5Y

How do i call "recall" method?

Please tell me how to call recall method.
I am new in Java.
I am making a program to display prime and composite number.
package composite;
import java.util.Scanner;
public class composite {
public static void main(String[] args) {
Scanner p = new Scanner(System.in);
System.out.println("press number till you want composite number & prime numbers");
int m=p.nextInt();int g[]=new int [m+1];prime(m);
for(int k=4;k<=m;k++)
{
for(int b=2;b<k;b++){
if(k%b==0){
g[k]=k;break;
}
}
}
}
public static int prime(int m){
int e[]= new int[m+1];
for(int i=2;i<m;i++)
{
int p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
e[i]=i;
}return(m);
}
public static int recall(int m, int [] e, int [] g){
for(int a=1;a<m;a++){
System.out.println(e[a]+" "+g[a]);
}
return m;
}
}
Take a look at following and modify the variables accordingly :
Composite call_recall = new Composite();
int recall_value = recall(m,e,g);
Place the proper values as you require in place of m, e and g.

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.

2d Array of Object Arrays

I want to make a 2D array of Arrays, each filled with another object. What I have so far is:
class CustomCache{
boolean dirty = false;
int age = 0;
String addr;
public CustomCache(boolean a, String b, int c){
dirty = a;
addr = b;
age = c;
}
}
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
Setup[][] array = new Setup[numSets][numBlocks];
for(int i=0; i<numSets; i++){
for(int j=0; j<numBlocks; j++){
array[i][j] = new Setup(wpb);
for(int k=0; k<wpb; k++){
array[i][j].wpbArray[k] = new CustomCache(false, "", 0);
}
}//end inner for
}//end outer loop
I keep getting a
java.lang.ArrayIndexOutOfBoundsException: 0
Which means the array is empty. Any idea of how to fix it?
This is the problem:
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
This line:
CustomCache[] wpbArray = new CustomCache[wpb];
runs before the body of the constructor - while wpb is still 0. You want:
class Setup {
int wpb;
CustomCache[] wpbArray;
public Setup(int a) {
wpb = a;
wpbArray = new CustomCache[wpb];
}
}
(I also suggest changing to more meaningful names, and using private final fields, but that's a different matter.)

Categories

Resources