Exception in main thread. Do not know the reason - java

package examples;
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
The below 4 sections identifies user input for the rows and columns of two matrices.
Scanner userrows1 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userrows1.nextInt();
Scanner usercolumns1 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns1 = usercolumns1.nextInt();
Scanner userrows2 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userrows2.nextInt();
Scanner usercolumns2 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns2 = usercolumns2.nextInt();
This sets the objects matrix1 and matrix2 as belonging to the class Matrix
Matrix matrix1 = new Matrix(rows1, columns1);
Matrix matrix2 = new Matrix(rows2, columns2);
matrix1.ShowMatrix();
System.out.println("\n \n");
matrix2.ShowMatrix();
}
}
class Matrix {
int rows;
int columns;
int[][] values;
public Matrix(int r, int c) {
rows = r;
columns = c;
int[][] values = new int[r][c];
This originally served to allow the user to input values of a matrix one by one. For now I just set all values of the matrix to a certain value for simplicity.
int i;
int j;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
//Scanner userelement = new Scanner(System.in);
//System.out.println("Enter number:");
//int element = userelement.nextInt();
values[i][j] = 1;
}
}
}
public void ShowMatrix() {
int k;
int l;
for(k = 0; k < rows; k++) {
for(l = 0; l < columns; l++) {
System.out.println(values[k][l] + " ");
}
System.out.println("\n");
}
}
}
The code is above. In the final method in the class Matrix (the method is ShowMatrix), I am trying to print out the matrix. However, I am using the general values matrix here and it says:
Exception in thread "main" java.lang.NullPointerException
at examples.Matrix.ShowMatrix(MatrixMultiplication.java:75)
at examples.MatrixMultiplication.main(MatrixMultiplication.java:29)
Can anyone diagnose the issue? Much thanks as I'm still very new to Java.

You've not instantiate the field [][]values (There is a local declaration of int[][] values).
public Matrix(int r, int c) {
rows = r;
columns = c;
int[][] values = new int[r][c]; <-- Remove this
values = new int[r][c];
....
}

Just remove the package line if you are using the terminal or command prompt.
package examples;
Working Code:
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner userrows1 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userrows1.nextInt();
Scanner usercolumns1 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns1 = usercolumns1.nextInt();
Scanner userrows2 = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userrows2.nextInt();
Scanner usercolumns2 = new Scanner(System.in);
System.out.println("Enter number of columns for matrix 2");
int columns2 = usercolumns2.nextInt();
Matrix matrix1 = new Matrix(rows1, columns1);
Matrix matrix2 = new Matrix(rows2, columns2);
matrix1.ShowMatrix();
System.out.println("\n \n");
matrix2.ShowMatrix();
}
}
class Matrix {
int rows;
int columns;
int[][] values;
public Matrix(int r, int c) {
rows = r;
columns = c;
//int[][] values = new int[r][c];
this.values = new int[r][c];
int i;
int j;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
this.values[i][j] = 1;
}
}
}
public void ShowMatrix() {
int k;
int l;
for(k = 0; k < this.rows; k++) {
for(l = 0; l < this.columns; l++) {
System.out.print(this.values[k][l] + " ");
}
System.out.println("\n");
}
}
}
One more suggestion is that there is no need of creating new instance/object for Scanner class for each row and column.
Scanner userInput = new Scanner(System.in);
System.out.println("Enter number of rows for matrix 1: ");
int rows1 = userInput.nextInt();
System.out.println("Enter number of columns for matrix 2");
int columns1 = userInput.nextInt();
System.out.println("Enter number of rows for matrix 2: ");
int rows2 = userInput.nextInt();
System.out.println("Enter number of columns for matrix 2");
int columns2 = userInput.nextInt();

Related

Moving my for loop into a different method and connecting it to main Java

I'm making a program using Java that calculates the sum of the numbers entered; I figured this part out. However, I want to move the for loop into a different method called "Sum", but I keep getting errors and I don't know what to do.
Here is the code thats only in the Main method (it works perfectly fine):
import java.util.Scanner;
public class testing {
public static void main(String args[]){
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
However, when I move the for loop into the method known as print, I get a bunch of errors:
import java.util.Scanner;
public class MPA4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
}
print(sum);
}
public static void print (double []sum){
Scanner in = new Scanner(System.in);
int myArray[] = new int [size];
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
Here are all the errors underlined in red:
I'm not sure what I'm doing wrong, any help would be much appreciated!
I changed it as below and it is working.
import java.util.Scanner;
public class MP4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int[size];
System.out.println("Enter the elements of the array one by one: ");
for (int i = 0; i < size; i++) {
myArray[i] = in.nextInt();
}
print(myArray, size);
}
public static void print(int[] myArray, int size) {
int sum = 0;
Scanner in = new Scanner(System.in);
for (int i = 0; i < size; i++) {
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: " + sum);
}
}

Error when trying to print a transposed 2d array

While writing my code I'm getting stuck on I'm trying to return the new transposed array and actually transposing the array itself. I get the error cannot convert int to int[][]. i thought trans would be an array var. the problem code is at the way bottom. any help is greatly appreciated.
package workfiles;
import java.util.*;
import java.util.Scanner;
public class hw2 {
// Do not modify this method
public static void main(String[] args) {
try
{
int [][] iArray = enter2DPosArray();
System.out.println("The original array values:");
print2DIArray(iArray);
int [][] tArray = transposition(iArray);
System.out.println("The transposed array values:");
print2DIArray(tArray);
}
catch (InputMismatchException exception)
{
System.out.println("The array entry failed. The program will now halt.");
}
}
// A function that prints a 2D integer array to standard output
// It prints each row on one line with newlines between rows
public static void print2DIArray(int[][] output) {
for (int row = 0; row < output.length; row++) {
for (int column = 0; column < output[row].length; column++) {
System.out.print(output[row][column] + " ");
}
System.out.println();
}
}
// A function that enters a 2D integer array from the user
// It raises an InputMismatchException if the user enters anything other
// than positive (> 0) values for the number of rows, the number of
// columns, or any array entry
public static int[][] enter2DPosArray() throws InputMismatchException {
int row=0;
int col=0;
int arow=0;
int acol=0;
int holder;
Scanner numScan = new Scanner(System.in);
while (row<=0){
System.out.print("How many rows (>0) should the array have? ");
row = numScan.nextInt();
}
while (col<=0){
System.out.print("How many columns (>0) should the array have? ");
col = numScan.nextInt();
}
int[][] iArray = new int[row][col];
while (arow < row) {
while (acol < col) {
System.out.println("Enter a positive (> 0) integer value: ");
holder = numScan.nextInt();
iArray[arow][acol] = holder;
acol++;
}
if (acol >= col) {
acol = 0;
arow ++;
}
}
//arrayName[i][j]
numScan.close();
return iArray;
}
//!!! problem code here!!!
public static int[][] transposition(int [][] iArray) {
int m = iArray.length;
int n = iArray[0].length;
int trans[][];
for(int y = 0; y<m; y++){
for(int x = 0; x<n; x++){
trans = iArray[y][x] ;
}
}
return trans;
}
}
You missed two things
1.) initialization of trans
int trans[][]= new int [n][m];
2.) trans is a 2D array
trans[y][x] = iArray[y][x] ;
//trans = iArray[y][x] ; error
Update : To form this logic , we need index mapping like this
// trans iArray
// assign values column-wise row-wise
// trans[0][0] <= iArray[0][0]
// trans[1][0] <= iArray[0][1]
// trans[2][0] <= iArray[0][2]
mean traverse the iArrays row-wise and assign values to trans array columns-wise
int m = iArray.length;
int n = iArray[0].length;
// iArray[2][3]
int trans[][] = new int[n][m];
// 3 2
for(int y = 0; y<m; y++){
for(int x = 0; x<n; x++){
trans[x][y] = iArray[y][x] ;
}
}

Filling a 2D Array with user input (integer to binary)

I have to take a user input of integers from a range, convert that to binary, and fill a 3x3 array with the binary. The only problem is, my code is giving me an output of only dependent on the first 3 numbers of that binary (i.e 010001101 = 010 across all rows).
import java.util.Scanner;
public class HW11P02 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
listArray(binary);
};
public static String[][] listArray(String binary) {
String[][] array = new String[3][3];
char ch = ' ';
String value = "";
for (int i = 0; i < 3; i++) {
for (int n = 0; n < 3; n++) {
ch = binary.charAt(n);
value = Character.toString(ch);
array[i][n] = value;
System.out.print(array[i][n] + " ");
}
System.out.println();
}
return array;
}
};
I think this will provide the the output you may really want.
import java.util.Scanner;
public class HW11P02
{
public static void main(String[] args)
{
Scanner in = new Scanner (System.in);
System.out.print("Enter a number between 0 and 511: ");
int n = in.nextInt();
String binary = Integer.toBinaryString(n);
binary = binary.format("%09d", Integer.parseInt(binary));
System.out.println(binary);
int result[][]=new int[3][3];
int position=0;
for (int i = 0; i < result.length; i++)
{
for (int j = 0; j < result.length; j++)
{
result[i][j]=binary.charAt(position++)-'0';
System.out.print(result[i][j]+" ");
}
System.out.println();
}
}
}

Create multiple arrays using a for loop

I would like to make a program where the user can input the number of variables and fill every variable with certain values. For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.
This is the code I was using, but it doesn't work:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
for(int j = 0;j < i;j++){
int[] var = new int[j];
System.out.println("Enter the number of values: ");
int p = s.nextInt();
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[q] = n;
}
}
}
And how could I compare these arrays that the user inputs?
The problem is that each time you are creating the array.
try this:
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[j][q] = n;
}
}
Instead of creating a one dimensional array, you create a jagged array. Essentially, a 2d array is an array of arrays. that way the user inputs the number of arrays (i) and then continues to fill the arrays.
To check whether two collections have no commons values, you can use
Collections.disjoint();
For other operations, you can look here
This should work (with bidimensionnal array)
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;q++){
int n = s.nextInt();
var[j][q] = n;
}
}
}
You have to replace the incrementation in the second loop too ("q++" instead of "p++")
This should work and solve their first point
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
while (p>0)
{
var[j] = new int[p];
for(int q=0;q < p;q++){
System.out.println("Value number : " +(q+1) + " For Array Number "+ (j+1));
int n = s.nextInt();
var[j][q] = n;
}
p-=1;
}
}

trying to fill a 2D array by user-input how to do it?

i am creating a code that allow user to enter his input to create a 2D array but it did not work as it should i do not know where is the problem if anyone can help me i will appreciate that.
this my code :
package test7;
import java.util.Scanner;
public class test7 {
private int row = 4;
private int col = 4;
private int[][] matrix;
public test7(int trow, int tcol) {
this.row = trow;
this.col = tcol;
}
public test7(int trow, int tcol, int[][] m) {
this.row = trow;
this.col = tcol;
this.matrix = m;
}
public int[][] fill(){
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in);
for(int row = 0; row< matrix.length; row++){
for(int col = 0 ;col< matrix[row].length; col++){
System.out.println("enter the elementss for the Matrix");
data[row][col] = in.nextInt();
}
System.out.println();
}
return data;
}
public static void main(String[] args){
int[][] ma = new int[3][2];
test7 q2 = new test7(3, 2,ma);
q2.fill();
}
}
the output:
enter the elementss for the Matrix
4
enter the elementss for the Matrix
3
enter the elementss for the Matrix
5
enter the elementss for the Matrix
8
enter the elementss for the Matrix
9
enter the elementss for the Matrix
0
the output should look exactly like this:
1 2
3 4
5 6
public int[][] fill(){
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in)
.....
return data;
}
You were declaring data array to length
[0][0]
This is why the error is. Change the statement to above given code.
UPDATE
public int[][] fill(){
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in);
for(int row = 0; row< matrix.length; row++){
for(int col = 0 ;col< matrix[row].length; col++){
System.out.println("enter the elementss for the Matrix");
data[row][col] = in.nextInt();
} System.out.println();
}
for(int row = 0; row< matrix.length; row++){
for(int col = 0 ;col< matrix[row].length; col++){
System.out.println(data[row][col]);
}
System.out.println();
}
return data;
}
This will give you the desired output , add it to fill method before the return statement
Replace your fill() method to this
public int[][] fill(){
int a[][]=new int[row][col];
Scanner input = new Scanner(System.in);
System.out.println("enter the elementss for the Matrix");
for(int row=0;row<3;row++){
for(int col=0;col<3;col++){
a[row][col]=input.nextInt();
}
}
return a;
}
Reason:
Your current fill() method is not saving values to the array
you must ad this line
a[row][col]=input.nextInt();
using
int x = in.nextInt();
system.out.print(x);
you are just entering the data again and again on the int variable x
Update
change this
int[][] data = new int[0][0];
to this
int[][] data = new int[row][col];
Try this:
System.out.println("enter the elementss for the Matrix");
Scanner in = new Scanner(System.in);
int[][] data = new int[matrix.length][];//note the change here
for(int i = 0; i< matrix.length; i++){
data[i]=new int[matrix[i].length]; // note the the change here
for(int j = 0 ;j< matrix[i].length; j++){
data[i][j] = in.nextInt(); // note the change here
}
system.out.println();
}
return data;

Categories