multiplying 2 matrices of different sizes in java - java

I am trying to multiply one matrix by another which are different sizes. The 1st matrix is 4 x 2, and the 2nd matrix is 2 x 2. Currently, the answer produced for this multiplication is by my program is not correct. Please help.
public class MatrixCipher {
public static void main(String[] args) {
int[][] matrix = new int[4][2];
int[][] matrix2 = new int[2][2];
matrix2[0][0] = 1;
matrix2[0][1] = 2;
matrix2[1][0] = 3;
matrix2[1][1] = 4;
int[][] product = new int[4][2];
for (int m = 0; m < 4; m++) {
for (int n = 0; n < 2; n++) {
matrix[m][n] = (int) (6 * Math.random() + 1);
}
}
System.out.print("==1==");
System.out.println(" ");
for (int m = 0; m < 4; m++) {
for (int n = 0; n < 2; n++) {
System.out.print(matrix[m][n] + " ");
}
System.out.println(" ");
}
System.out.print("=====");
System.out.println("");
System.out.println(" x");
System.out.print("==2==");
System.out.println(" ");
for (int m = 0; m < 2; m++) {
for (int n = 0; n < 2; n++) {
System.out.print(matrix2[m][n] + " ");
}
System.out.println(" ");
}
System.out.print("=====");
System.out.println("");
System.out.println(" =");
for (int m = 0; m < 4; m++) {
for (int n = 0; n < 2; n++) {
for (int f = 0; f < 2; f++) {
product[m][n] = matrix[m][n] * matrix2[f][n];
}
}
}
System.out.print("=====");
System.out.println(" ");
for (int m = 0; m < 4; m++) {
for (int n = 0; n < 2; n++) {
System.out.print(product[m][n] + " ");
}
System.out.println(" ");
}
System.out.print("=====");
System.out.println("");
}
}

You miss the whole addition part and use a wrong order during the mutliplication.
for (int m = 0; m < 4; m++) {
for (int n = 0; n < 2; n++) {
for (int f = 0; f < 2; f++) {
product[m][n] = product[m][n] + matrix[m][f] * matrix2[f][n];
}
}
}

Related

String,which repeats ,but not starts from the beginning in Java (diamond pattern

This is the work that i done so far:I have to print diamond pattern which always starts with uppercase from string, which repeats,but not always starts from the beginning.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
userInput = Character.toUpperCase(userInput.charAt(0)) + userInput.substring(1);
int i;
int j;
if (userInput.length() % 2 != 0) {
for(i = 1; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
} else {
for(i = 2; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
}
}
For example my input is "Peter".
So my output is:
P
Pet
Peter
Pet
P
but it must be:
P
Ete
Rpete
Rpe
T
I dont know what to change to make this work
Here's a shorter version of your code:
public static void main(String[] args) {
String userInput = "Peter";
int length = userInput.length();
int m, j, i, n = 0;
for (m = length % 2 > 0 ? 1 : 2; m < length * 2; m += 2) {
i = m < length ? m : length * 2 - m;
for (j = 0; j < length - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
char c = userInput.charAt(n++ % length);
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
}
System.out.println("");
}
}
You need some few changes:
Declare int n=0; after int j;
Always print userInput.charAt(n++ % userInput.length()) instead of charAt(j)
In order to get only the first character in line in uppercase:
char c = userInput.charAt(n++ % userInput.length());
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
Check the modulo operator.
With these changes, you'll get this output:
P
Ete
Rpete
Rpe
T
Given the fact that the input itself gets printed in a cylic manner, we can make use out of it. My proposal would be to concatenate the input string and print out the substrings which are determined by the structure of the diamond pattern.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
String concatenated = userInput;
// build up the index array
int i, cumSum = 0;
ArrayList<Integer> helperIndex = new ArrayList<>();
for(i = 1; i < userInput.length(); i += 2) {
helperIndex.add(i);
cumSum += i;
}
for(i = userInput.length(); i > 0; i -= 2) {
helperIndex.add(i);
cumSum += i;
}
int numOfWordRepitition = cumSum / userInput.length() ;
for (i = 0; i < numOfWordRepitition; i++){
concatenated += userInput;
}
// print out diamond
String substr;
int prev = helperIndex.get(0);
int next = helperIndex.get(0);
substr = concatenated.substring(0 , helperIndex.get(0));
System.out.println(Character.toUpperCase(substr.charAt(0)) + substr.substring(1));
for(i = 1; i < userInput.length(); i++){
next += helperIndex.get(i);
substr = concatenated.substring(prev , next);
substr = Character.toUpperCase(substr.charAt(0)) + substr.substring(1);
System.out.println(substr);
prev = next;
}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 error

I wrote a code for minesweeper problem. It creates an MxN minesweeper game where each cell is a bomb with probability p. Prints out the m-by-n game and the neighboring bomb counts.
Code:
class Minesweeper {
public static void main(String[] args) {
int m = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);
try {
boolean[][] bombs = new boolean[m+2][n+2];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
bombs[i][j] = (Math.random() < p);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++)
if (bombs[i][j]) System.out.print("* ");
else System.out.print(". ");
System.out.println();
}
int[][] sol = new int[m+2][n+2];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
// (ii, jj) indexes neighboring cells
for (int ii = i - 1; ii <= i + 1; ii++)
for (int jj = j - 1; jj <= j + 1; jj++)
if (bombs[ii][jj]) sol[i][j]++;
System.out.println();
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (bombs[i][j]) System.out.print("* ");
else System.out.print(sol[i][j] + " ");
}
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Do I need to give any condition after parsing?
int m = Integer.parseInt(args[0]);
int n = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);
Please help me.
Just give a extra condition before parsing the argument.
if (args.length >= 3) {
m = Integer.parseInt(args[0]);
n = Integer.parseInt(args[1]);
p = Double.parseDouble(args[2]);
}

How to create public array accessible by all methods, but have user input determine the size of it?

I have multiple arrays whose sizes need to be determined by the user input. These arrays should be accessible in the main method as well as the stepTwo() method. However, I am stuck. The user input doesn't come until the main method, but if I declare the arrays in the main method, then I can't access the arrays in the stepTwo() method. I would prefer not to pass the arrays as parameters to stepTwo() as I tried that before but came up with multiple errors. Any suggestions? See below for complete code:
public class AssignmentIII
{
public static int numProcesses; // Represents the number of processes
public static int numResources; // Represents the number of different types of resources
public static int[] available = new int[numResources]; // Create an emptry matrix for available processes
public static int[][] allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
public static int[][] request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
public static int[] work = new int[numResources]; // Create an empty work matrix
public static Boolean[] finish = new Boolean[numProcesses]; // Create an empty finish matrix
public static void main(String[] args) throws FileNotFoundException
{
try
{
Scanner scan = new Scanner(System.in);
Scanner fileScan = new Scanner(new File("input1.txt")); // Create file scanner
System.out.println("Please enter the total number of processes: ");
numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
numResources = scan.nextInt();
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
// Begin deadlock detection algorithm
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
stepTwo();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
}
public static void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
}
Declare the array as you do - "above main", but initialize it after reading in the appropriate size.
Declaration:
public static int[] available;
Initialization:
available = new int[numResources];
you must initialize the array into de main block, something like this.
public class AssignmentIII
{
public static int numProcesses; // Represents the number of processes
public static int numResources; // Represents the number of different types of resources
public static int[] available ;
public static int[][] allocation ;
public static int[][] request ;
public static int[] work ;
public static Boolean[] finish ;
public static void main(String[] args) throws FileNotFoundException
{
try
{
Scanner scan = new Scanner(System.in);
Scanner fileScan = new Scanner(new File("input1.txt")); // Create file scanner
System.out.println("Please enter the total number of processes: ");
numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
numResources = scan.nextInt();
available = new int[numResources]; // Create an emptry matrix for available processes
allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
work = new int[numResources]; // Create an empty work matrix
finish = new Boolean[numProcesses]; // Create an empty finish matrix
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
// Begin deadlock detection algorithm
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
stepTwo();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
}
public static void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
}
but this, is not a recommended way. Because is not the right way for use the static method and static attribute. Furthermore you should use encapsulation.
Using a better design and encapsulation method, your code can be improved something like this.
public class AssignmentIII
{
int numProcesses; // Represents the number of processes
int numResources; // Represents the number of different types of resources
String filepath;
int[] available = new int[numResources]; // Create an emptry matrix for available processes
int[][] allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
int[][] request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
int[] work = new int[numResources]; // Create an empty work matrix
Boolean[] finish = new Boolean[numProcesses]; // Create an empty finish matrix
public AssignmentIII(int numResources,int numProcesses, String filepath){
this.numProcesses = numProcesses;
this.numResources = numResources;
this.filepath = filepath;
available = new int[numResources]; // Create an emptry matrix for available processes
allocation = new int[numProcesses][numResources]; // Create an empty allocation matrix nxm
request = new int[numProcesses][numResources]; // Create an empty request matrix nxm
work = new int[numResources]; // Create an empty work matrix
finish = new Boolean[numProcesses]; // Create an empty finish matrix
}
public void initilizeMatrix() throws FileNotFoundException{
Scanner fileScan = new Scanner(new File(filepath)); // Create file scanner
// Initialize the available matrix
for(int i = 0; i < numResources; i++)
available[i]=fileScan.nextInt();
// Initialize the allocation matrix
for(int j = 0; j < numProcesses; j++)
for(int k = 0; k < numResources; k++)
allocation[j][k]=fileScan.nextInt();
// Initialize the request matrix
for(int m = 0; m < numProcesses; m++)
for(int n = 0; n < numResources; n++)
request[m][n]=fileScan.nextInt();
fileScan.close();
}
public void print(){
// Print allocation matrix
System.out.println();
System.out.println("Allocated");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int j = 0; j < numProcesses; j++)
{
System.out.print("P" + j);
for(int k = 0; k < numResources; k++)
{
System.out.print("\t" + allocation[j][k]);
}
System.out.println();
}
// Print available matrix
System.out.println();
System.out.println("Available");
for(int i = 0; i < numResources; i++)
{
System.out.print("R" + i + "\t");
}
System.out.println();
for(int i = 0; i < numResources; i++)
System.out.print(available[i] + "\t");
System.out.println();
// Print request matrix
System.out.println();
System.out.println("Requested");
for(int i = 0; i < numResources; i++)
{
System.out.print("\tR" + i);
}
System.out.println();
for(int m = 0; m < numProcesses; m++)
{
System.out.print("P" + m);
for(int n = 0; n < numResources; n++)
{
System.out.print("\t" + request[m][n]);
}
System.out.println();
}
System.out.println();
}
// Begin deadlock detection algorithm
public void deadLockdetecter(){
for(int i = 0; i < numResources; i++) // Intialize Work := Available
work[i]=available[i];
for(int j = 0; j < numProcesses; j++) // Check for Allocation != 0 and initialize Finish accordingly
{
int sumAllocation = 0;
for(int i = 0; i < numResources; i++)
{
sumAllocation += allocation[j][i];
}
if (sumAllocation != 0)
finish[j] = false;
else finish[j] = true;
}
}
public void stepTwo()
{
// Step 2
// Find an index i where Finish[i] = false & Request[i] <= Work
for(int i = 0; i < numProcesses; i++)
{
int sumRequests = 0;
int sumWork = 0;
// Sum the Request and Work vectors
for(int k = 0; k < numResources; k++)
{
sumRequests += request[i][k];
sumWork += work[k];
}
if (finish[i] == false && sumRequests <= sumWork)
{
finish[i] = true;
for(int m = 0; m < numResources; m++)
{
work[m] = work[m] + allocation[i][m];
}
stepTwo();
}
else if (finish[i] == false)
// Step 4: Print which processes are in a deadlock state
// Print using P0, P1, ... , Pn format
System.out.println("P" + i + " is in a deadlock state.");
}
}
public static void main(String[] args) throws FileNotFoundException
{
AssignmentIII assignment;
String p_filepath;
int p_numProcesses;
int p_numResources;
p_filepath = "inpu1t.txt";
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the total number of processes: ");
p_numProcesses = scan.nextInt();
System.out.println("Please enter the number of different types of resources: ");
p_numResources = scan.nextInt();
scan.close();
assignment = new AssignmentIII(p_numResources, p_numProcesses, p_filepath);
try
{
assignment.initilizeMatrix();
}
catch(FileNotFoundException ex)
{
System.out.println("An error has occured. The file cannot be found.");
}
assignment.stepTwo();
}
}

Java Index out of bound error matrix multiplication

I am getting an index out of bound error for this.
I set on netbeans the argument on the project and works fine.
But how can i set an argument for n within the code without going on the project properties and changing the value there?
When i try to put static int N = 4 ; i get error throughout code, can someone help me please?
package matrix;
// performing matrix multiplication parallely by using two threads
// In thread 1 we will multiply matrix a and b and store in C with range of 0 to N/2
// In thread 2 we will multiply matrix a and b and store in C with range of N/2 to N
// For our convenience I'm used 4 instead of N ( we can replace 4 with N)
public class Mymainclass implements Runnable {
static int n;
// a and b are input matrix's
static int a[][];
static int b[][];
/* we will multiply the elements in a and b matrix's
* parallely by using two threads
and will store in the c matrix sequentially.*/
static int c[][];
public Mymainclass(int n1) {
n = n1;
a = new int[n][n];
b = new int[n][n];
c = new int[n][n];
}
public void run() {
int i, j, k;
System.out.println("in thread1 class");
for (i = 0; i < this.n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
this.c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.print("\n");
System.out.println("Matrix c in thread1");
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
System.out.print(c[a][b] + " ");
}
System.out.print("\n");
}
}
public static void main(String[] args) {
String n1 = args[0];
n = Integer.parseInt(n1);
System.out.println(n);
Mymainclass th1 = new Mymainclass(n);
int z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = z++;
}
System.out.print("\n");
}
z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[i][j] = z++;
}
System.out.print("\n");
}
System.out.println("Matrix a");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
System.out.println("Matrix b");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
Thread t = new Thread(th1);
t.start();
}
}
That is working for me:
public class Mymainclass implements Runnable {
static int n;
// a and b are input matrix's
static int a[][];
static int b[][];
/* we will multiply the elements in a and b matrix's
* parallely by using two threads
and will store in the c matrix sequentially.*/
static int c[][];
public Mymainclass(int n1) {
n = n1;
a = new int[n][n];
b = new int[n][n];
c = new int[n][n];
}
public void run() {
int i, j, k;
System.out.println("in thread1 class");
for (i = 0; i < this.n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
this.c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.print("\n");
System.out.println("Matrix c in thread1");
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
System.out.print(c[a][b] + " ");
}
System.out.print("\n");
}
}
static int N = 4 ;
public static void main(String[] args) {
Mymainclass th1 = new Mymainclass(N);
int z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = z++;
}
System.out.print("\n");
}
z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[i][j] = z++;
}
System.out.print("\n");
}
System.out.println("Matrix a");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
System.out.println("Matrix b");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
Thread t = new Thread(th1);
t.start();
}
}
For measuring time just change code where you start thread to:
ExecutorService service = Executors.newSingleThreadExecutor();
long start = System.currentTimeMillis();
Future<?> future = service.submit(th1);
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("time: " + (System.currentTimeMillis() - start));
service.shutdown();

Cannot get the addition to output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet

Categories

Resources