+ 4
Addition of array elements in Java.
Hi! I need help in a program. It has 2 2*2 array. The program asks to input their value and then adds the two matrix elements to the other. Program should looks like this. Please give the first matrix elements: 1 2 3 4 Please give the second matrix elements: 5 -1 3 -4 The result: 6 1 6 0 Also the result must not contain whitespace at the end of the line. The numbers are integers. int [][] firstMatrix = new int [1][1]; int [][] secondMatrix = new int [1][1]; This code is good to create the 2*2 array? How to input their values by user? Thanks in advance!
2 Answers
+ 6
Hello, one way to prompt the user to input values in your code is by importing and getting a Scanner like so:
import java.util.Scanner;
//Get a new Scanner next:
Scanner test = new Scanner(System.in);
//Save/ask for input:
String word = test.next();
//If it's a number:
int number = test.nextInt();
Note: since you want to fill up a matrix by multiple inputs from the user, it may be an option to create several 'for' loops (even nested). In pseudo-code:
For i=0 until you reach the length of the array, ask for user input.
Sorry for the long post, hope that helps and good luck!
+ 2
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int [][] firstMatrix = new int [2][2];
int [][] secondMatrix = new int [2][2];
System.out.println("Please give the first matrix elements:");
for (int i= 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
int number = sc.nextInt();
firstMatrix [i][j] = number;
}
}
System.out.println("Please give the second matrix elements:");
for (int i= 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
int number = sc.nextInt();
secondMatrix [i][j] = number;
}
}
System.out.println("The result:");
System.out.print((firstMatrix[0][0] + secondMatrix[0][0]) + " " + (firstMatrix[0][1] + secondMatrix[0][1]));
System.out.println();
System.out.print((firstMatrix[1][0] + secondMatrix[1][0]) + " " + (firstMatrix[1][1] + secondMatrix[1][1]));
}
}
Working perfectly, thanks for help!