multiplication of 2-dimensional array java - java

I want to enter 2 dimensional arrays by joptionpane and display the multiplication of it by java,
I tried do this but I don't no why the result always is (0 0 0),I think that the result arrays is empty! could anyone help me ....!!??
System.out.print("can not multiply");
}
public static double[][] multiplyMatrix(double[][] x, double[][] z) {
double[][] result = new double[x.length][z[0].length];
for (int i = 0; i < x.length; i++)
for ( int j = 0; j <z[0].length; j++){
result[i][j]=0;
for (int k = 0; k < z.length; k++)
result[i][j] += x[i][k] * z[k][j];}
return result;
}

You populate your A array in both of your for loops. You have to populate B in the second for loop.
double[][] B = new double[n2][m2];
int k;
int l;
for (k = 0; k < n2; k++) {
for (l = 0; l < m2; l++) {
String s1 = JOptionPane.showInputDialog("Enter B" + "[" + (k) + (l) + "]" + " element ");
//A[k][l] = Integer.parseInt(s1); //This should be populating B
B[k][l] = Integer.parseInt(s1); //Change it to this
}
}
After fixing that issue, you still have some bugs in your multiplication method. But now that you actually get a result array, you can debug it pretty easily.
Hope this helps.

Related

Basic array - Java

I need to make 2 arrays called A and B, both of type int with size 100. Each index should be a random number between 0 and 100 inclusive and then compare both arrays, and say how many times 2 of the same number appeared in both arrays.
This is what I have so far
int count = 0;
int [] A = new int [100];
int [] B = new int [100];
for(int i = 0; i < A.length; i++){
A [i] = (int)(Math.random()*101);
System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
B [i] = (int)(Math.random()*101);
System.out.println("Array B: " + i);
}
if(A [i] == B [i]){
count++;
}
I'm not sure how to show how many times 2 of the same number appeared in both arrays.
You need to loop through both of the arrays:
int count = 0;
int [] A = new int [100];
int [] B = new int [100];
for(int i = 0; i < A.length; i++){
A [i] = (int)(Math.random()*101);
System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
B [i] = (int)(Math.random()*101);
System.out.println("Array B: " + i);
}
// Loop through the first array
for(int i = 0; i < A.length; i++) {
// For each element in the first array, loop through the whole second one
for (int j = 0; j < B.length; j++) {
// If it's a match
if(A[i] == B[j])
count++;
}
}
System.out.println("Count: " + count);
Alternatively, if you don't need the 2 arrays, you can simply do:
int count = Random.ints(100, 0, 101).boxed().collect(toSet())
.retainAll(Random.ints(100, 0, 101).boxed().collect(toSet()))
.size();
You started off nicely, but you need a nested for-loop to check each of the indexes.
ALSO-- make sure that in your arrays you print out A[i] and B[i] otherwise you're just printing out the number of the index as opposed to the number inside the index.
int count = 0;
int[] A = new int[100];
int[] B = new int[100];
//Create the first array
for (int i = 0; i < A.length; i++) {
A[i] = (int)(Math.random() * 101);
System.out.println("Array A: " + A[i]);
}
//Create the second array
for (int i = 0; i < B.length; i++) {
B[i] = (int)(Math.random() * 101);
System.out.println("Array B: " + B[i]);
}
//Check the indexes and make sure they are all compared-- 10,000 comparisons are made
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if(A[i] == B[j])
count++;
}
}
Hopefully that posted correctly... first time posting code on this website, but I hope that I was of help!
Keep in mind if the same number is being posted twice, you're going to get counts over 100.
Good luck!

ArrayIndexOutOfBoundsException Java Issue

So I have been working on this problem for a while now. I keep getting an ArrayIndexOutOfBoundsException but I am unable to locate where the issue lies. If someone could point me in the right direction, I would really appreciate it! Thanks!
public class Answer {
public static void main(String[] args){
double[] y = {23, 11.1, 50.4};
double[] x = {22.2, 46, 100.0};
Answer answer = new Answer();
answer.answer(y, x);
}
public static int answer(double[] y, double[] x) {
int result = 0;
double percent_1, percent_2;
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
// Calculate percent of first 2 x value array items with y
// all y values. Store the results in a seperate list.
for(int i = 0; i < x.length; i++){
percent_1 = compare(y[i], x[0]);
percent_2 = compare(y[i], x[1]);
compareList_1[i] = percent_1;
compareList_2[i] = percent_2;
}
// Compare those lists to find common number
// There you have your answer.
result = (int)compareLists(compareList_1, compareList_2);
return result;
}
// Calculates percentage from x and y values
public static double compare(double y, double x){
double result = 1 - (y/x);
return result;
}
// Finds common value in lists
public static double compareLists(double[] list_1, double[] list_2){
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
if(list_1[i] == list_2[j]){
return list_1[i];
}
}
}
// Just cus this shouldn't ever return.
return 100;
}
}
In your iteration (compareLists), you should use 'length' (not length + 1)
for(int i = 0; i < list_1.length; i++)
for(int j = 0; j < list_2.length; i++)
I think the problerm is in
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
i < list_1.length + 1 or j < list_2.length + 1 change it to
for(int i = 0; i < list_1.length; i++){
for(int j = 0; j < list_2.length ; j++){
remove +1 from each condition.For j < list_2.length + 1 the list_2.length will give you length of array ie lastIndex +1 and you are adding another +1 in it causing loop condition to be j<lastIndex +1 giving you index error on the last iteration of loop in the line if(list_1[i] == list_2[j]){ for list_2[j]
Also in answer method you declare array by
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
and in the loop you are iterating upto x.length if x.length is greater than y.length the you can get the Index error in compareList_2[i] = percent_2;(inside the loop) because its length is y.length.

Multidimensional Array Java

I am writing a program using a method that returns the location of the largest element in a two dimensional array.
Example:
Enter the number of rows and columns of the array:
3 4
Enter the array:
23.5 35 2 10
4.5 3 45 3.5
35 44 5.5 9.6
the location of the largest element is at (1, 2)
My code is working, but I'm getting the output wrong. Instead of numbers I am getting some weird output with letters and numbers. How can I fix it? Thanks!
My code
import java.util.Scanner;
public class homework1a {
public static int[] locateLargest(double[][] a)
{
int total = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
maxRow = i;
maxColumn = j;
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
public static void main(String[] args)
{
//Create Scanner
Scanner input = new Scanner(System.in);
double b = 0;
//User input rows and columns
System.out.println("Enter the number of rows and columns in the array: ");
int numberOfRows = input.nextInt();
int numberOfColumns = input.nextInt();
//User input data in array
System.out.println("Enter numbers into array: ");
//Create array
double[][] a = new double[numberOfRows][numberOfColumns];
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
a[i][j] = input.nextDouble();
}
}
System.out.println("The location of the largest element is at "+ locateLargest(a));
}
}
Your method locateLargest() returns an int-array, which you are implicitly converting to string while printing it.
I think you want to display the row and cell numbers inside the array:
int[] largest = locateLargest(a);
System.out.println(String.format("The location of the largest element is at %d,%d", largest[0], largest[1]));
locateLargest(a) returns an int[2]. Arrays cannot be converted to strings natively, so the default toString() implementation is invoked on the array. The returned string representation does not contain the array elements.
This question might help you to print a helpful representation of the array. You might also want to print both values independently, not the array as a whole, e.g. like this:
int[] pos = locateLargest(a);
System.out.println("The location of the largest element is at " + pos[0] + ":" + pos[1]);
To print Arrays use Arrays.toString(array) output will be like [x,y]
System.out.println("The location of the largest element is at "+ Arrays.toString(locateLargest(a)));
Your method locateLargest returns an int[] which will not be printed out nicely.
If you want to keep the signature of locateLargest as it is, you could change your code in main like this:
int[] positionOfLargest = locateLargest(a);
System.out.println("The location of the largest element is at " +
positionOfLargest[0] + "/" + positionOfLargest[1]);
This stores the result in positionOfLargest and then prints out x/y coordinates the way you want them.
Hey for finding largest you can have your method like this.
public static int[] locateLargest(double[][] a)
{
int maxValue = 0;
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
If(a[i][j] > maxValue)
{
maxValue = a[i][j] ;
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
return largest;
}
u should edit your locateLargest as this:
public static int[] locateLargest(double[][] a)
{
//may be ur array is contain negative
//so u can not use zero as MAX it's better to use first array element
int MAX = a[0][0];
int maxRow = 0;
int maxColumn = 0;
for (int i = 0; i < a.length; i++)
{
for (int j = 0; j < a[i].length; j++)
{
if(MAx < a[i][j]){
maxRow = i;
maxColumn = j;
}
}
}
int[] largest = new int[2];
largest[0] = maxRow;
largest[1] = maxColumn;
String result="location of largest num =a["+maxRow+"]["+maxColumn+"]";
return largest;
}

Matrix calculation not working... very odd output Java

This is what I want to do when A is a square matrix.
P - is power.
A & B are square matrices.
User will be asked to enter size of matrix A, and elements of matrix A and to what power they want to raise the matrix to.
Once they input what power, and what elements my program is supposed to calculate this:
(Assuming P = 5)
A^5 + A^4 + A^3 + A^2 + A
I have written a method that adds matrices a method that multiplies them, and a method that raises them to the power and they all work correctly.
The problem I am having is the final step which I showed above A^5 + A^4 + A^ 3...
This is where the problem gets even weirder, my program works when the elements in the matrix are all the same... such that a
2 2 2
2 2 2
2 2 2
matrix will give me the CORRECT output, BUT
1 2 3
4 5 6
7 8 9
matrix will give me the WRONG output and I have no idea why.
This is the method in which the problem is occuring
public static void addPowers(int [][] a, int[][] b, int p) {
while( p != 1){
b = addMatrices(powerMatrix(a,p), b) ;
addPowers(a,b,p-1) ;
return ;
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++)
System.out.print(b[i][j] + "\t") ;
System.out.println();
}
}
Just in case you ask, reason I have the recursive under a while loop is so it won't print over and over and over again.
Thanks for your time! :)
Edit: More clarifying information.
addMatrices is a method that adds matrices with an two int[][] arguments.
powerMatrix is a method that finds the power of a matrix with (int[][], int) arguments.
EDIT Methods being called...
public static int[][] multiplyMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int matrix[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++)
{
for (int l = 0; l < matrixA.length; l++)
{
sum += matrixA[i][l] * matrixB[l][j] ;
}
temp[i][j] = sum ;
sum = 0 ;
}
}
matrix = temp;
return matrix ;
}
public static int[][] addMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++) {
{
sum = matrixA[i][j] + matrixB[i][j] ;
}
temp[i][j] = sum ;
}
}
return temp ;
}
public static int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; n++)
result = multiplyMatrices(result, a);
return result;
}
In your addMatrices method, you should remove the third loop.
Like this:
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {
temp[i][j] = matrixA[i][j] + matrixB[i][j] ;
}
}

Why does my Java "for" loop immediately end?

My first loop seems to build the array correctly and when I go to print out the results in the second "for" loop it immediately terminates. I cannot see the error. Here is the code:
public class CoinFlip
{
private static int Flip()
{
return (int)(2*Math.random()); //returns 0 or 1; 0=Tails,1=Heads
}
public static void main(String args[])
{
int HEADS = 1;
int[] ConsecArray = new int[1000]; // the odds of ever having more than 1000 HEADS consecutively flipped are nil
int Sequencecounter = 0;
for (int i = 0; i < ConsecArray.length; i++)
{
if (Flip() == HEADS)
{
Sequencecounter++;
}
else // we have a TAILS
{
// Check sequence counter, if > 0, logging to do...
if (Sequencecounter > 0)
{
// Update length counters
int index = Sequencecounter - 1;
ConsecArray[index]++;
Sequencecounter = 0;
}
// consecutive tails, continue in loop
}
}
int j = ConsecArray.length;
System.out.println("Length" + " " + "NumberRunsOfHeads");
for (int k = 0; k == j; k++)
{
int index = k + 1;
String bucketName = Integer.toString(index);
String bucketValue = Integer.toString(ConsecArray[k]);
System.out.println(bucketName + " " + bucketValue);
}
}
}
The first iteration of your 2nd loop:
k is 0
j is 1000
the test k == j fails
the loop never runs
Change
for (int k = 0; k == j; k++)
into
for (int k = 0; k < j; k++)
I think you mean either k <= j or k < j, but you put k == j. This is not true during first iteration, so loop body never executes.
for (int k = 0; k == j; k++)
{
int index = k + 1;
String bucketName = Integer.toString(index);
String bucketValue = Integer.toString(ConsecArray[k]);
System.out.println(bucketName + " " + bucketValue);
}
Instead of for (int k = 0; k == j; k++) (which is equivalent to if (k == j)) you meant to write or for (int k = 0; k < j; k++), i.e. loop j times, not loop as long as k == j.
This:
for (int k = 0; k == j; k++)
Should be this:
for (int k = 0; k < j; k++)
kett_chup is right. I Think you want "k < j". You're thinking of "until" rather than "for".

Categories