Printing a 2 dimensional constructor in Java - java

I'm need to print the values of the 2d array in the constructor from the main method. Everytime I call the mainSc array, I get a value of null for each value in the 2d array. Why is that and how do I fix the array to call values from the constructor?
public class Main {
public static void main(String[] args) {
String[][] mainSc = new String[5][5];
System.out.println(Arrays.deepToString(mainSc));
}
}
import java.util.Arrays;
public class Schedule {
private int numDays;
private int numClasses;
private String[][] Cal;
public Schedule(String[][] array) {
this.numDays = 5;
this.numClasses = 4;
this.Cal = array;
}
public String[][] Array() {
for (int r = 0; r < numDays; r++){
for (int j = 0; j <= numClasses; j++){
this.Cal[0][0] = "Monday";
this.Cal[1][0] = "Tuesday";
this.Cal[2][0] = "Wednesday";
this.Cal[3][0] = "Thursday";
this.Cal[4][0] = "Friday";
}
}
return this.Cal;
}
public void printSchedule() {
for (int r = 0; r <= numDays; r++){
for (int j = 0; j <= numClasses; j++){
System.out.println(this.Cal[r][j]);
}
}
}
}

Declaring an array reference variable does not create an array. The next step in the process is to use the new keyword to create an array and assign its address to the variable. You should also include the dimensions for the array.
private String[][] cal = new String[5][5];

Related

How do I construct an array and initialize it to the values 1 through 5 using a loop?

This is what I have so far, but I keep getting a NullPointException error.
public class Array
{
private int[] val;
public Array()
{
for (int i = 0; i < val.length; i++){
if (i < 4) {
System.out.print(",");
}
int[] val = new int[i];
}
}
A proper way to do this is
public class MyArray
{
private int[] val;
public MyArray()
{
val = new int [5]; // create an array of 5, all zero values at this stage
for (int i = 0; i < val.length; i++){
val [i] = i + 1;
}
}

Passing an array and variable to a method and returning a smaller array

Had no luck the first time I had posted my question so I thought I would try again. I am a new Java programmer working on a little segment of code currently. In short I have created an array and a variable, what I would like this program to do is take the array and variable, pass it down to a method, have the method look at the array and if any of the numbers in the array are the same as the variable "8", take them out of the array "create a new array" return this array back to main and print it out.
I would like the array {2,4,8,19,32,17,17,18,25,17,8,3,4,8} to display {2,4,19,32,17,17,18,25,17,3,4} after being passed back to main please explain to me what I am doing wrong keep in mind I am brand new to java.
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < arrayA.length; x++)
{
System.out.print(arrayA[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
int index = 0;
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
index++;
}
}
return arrayX;
}
}
Simple one liner should suffice:
public static int[] newSmallerArray( int[] arrayA, int varB)
{
return Arrays.stream(arrayA).filter(i -> i != varB).toArray();
}
you missed to initialize array arrayX, try following solution
public class Harrison7b
{
public static void main(String [] args)
{
int[] arrayA = {2,4,8,19,32,17,17,18,25,17,8,3,4,8};
int varB = 8;
// Call with the array and variable you need to find.
int[] result = newSmallerArray(arrayA, varB);
for(int x = 0; x < result.length; x++) {
System.out.print(result[x] + " ");
}
}
public static int[] newSmallerArray( int[] arrayA, int varB)
{
int count = 0;
for(int x = 0; x < arrayA.length; x++)
{
if(arrayA[x] == varB)
{
count++;
}
}
int [] arrayX = new int[arrayA.length - count];
int index = 0;
for(int B = 0; B < arrayA.length; B++)
{
if(arrayA[B] != varB)
{
arrayX[index]= arrayA[B];
index++;
}
}
return arrayX;
}
}

calculate the minimum value for each column in 2D array

I have a 2D array , iam trying to calculate the minimum value for each column and put the result in the result array.
the code bellow is calculating the minimum value for each row , how can i get the min value for each column.
import java.util.*;
class Test20 {
public static void main ( String [] args) {
int[][] array = {{6,3,9},
{0,8,2},
{3,7,5}};
Test20 test = new Test20();
System.out.print(Arrays.toString(test.mincol(array)));
}
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
}
Just change the loop the following way:
min = 0;
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[j][min]){
min=j;
}
result[i]=n[min][i];
}
Be aware that you instantiate your result array by the length of the first dimension in your array but later use the n[][] param for looping and access the length of the second dimension in your loop.
If your two dim array is for example 4x5, this will cause ArrayOutOfBoundsExceptions.
You only need to do the same thing but inverting the variables
for(int i=0;i<n.length;i++){
for(int j=0;j<n[0].length;j++){
if(n[j][i]<n[min][j]){
min=i;
}
result[j]=n[min][j];
}
}
If your code is correct just change:
if(n[i][j]<n[i][min]){
min=j;
}
with
if(n[i][j]<n[result[i]][j]){
result[i]=i;
}
finally
for(int i=0;i<n.length;i++) result[i]=n[result[i][j];
you don't need min. But change
int [] result = new int[n.length];
to
int [] result = new int[n[0].length];
How about you transpose your two dimensional array like:
public static int[][] transpose (int[][] original) {
int[][] array = new int[original.length][];
// transpose
if (original.length > 0) {
for (int i = 0; i < original[0].length; i++) {
array[i] = new int[original[i].length];
for (int j = 0; j < original.length; j++) {
array[i][j] = original[j][i];
}
}
}
return array;
}
and then call it as:
System.out.print(Arrays.toString(test.minrow(transpose(array))));
Or, if you want to go without transpose, this is how you can do:
public static int[] mincol (int[][] n) {
int[] result = new int[n.length];
for (int i = 0; i < n.length; i++) {
int min = n[0][i];
for (int j = 0; j < n[0].length; j++) {
if (n[j][i] < min) {
min = n[j][i];
}
}
result[i] = min;
}
return result;
}
Your for loop looks ok. Check the code below I fixed some minor issues.
Based on your code replace Class code with below:
public class Test {
public static void main(String[] args) {
int[][]array={{6,1,9}, {0,1,2}, {3,7,5}};
int[] test;
test = minrow(array);
for(int i=0; i<test.length; i++){
System.out.println(test[i]);
}
}
public static int[] minrow(int[][] n){
int [] result = new int[n.length];
int min;
for(int i=0;i<n.length;i++){
min=0;
for(int j=0;j<n[i].length;j++){
if(n[i][j]<n[i][min]){
min=j;
}
}
result[i]=n[i][min];
}
return result;
}
}

two quick fix issues - Merge Sort

I have created my version of the merge sort algorithm in java code. My issues are these: when I run the code as is, I get a NullPointerExecpetion in the main on line 27 (see commented line). And I know there is way to make the method calls and instantiate newArray without them being static but Im not quite sure how.. can someone help fix these? I am still relatively new to java so be nice :)
Main:
import java.util.Random;
public class MergeSort_main
{
public static void main(String[] args)
{
int[] originalArray = new int[1000];
Random rand = new Random();
for (int i = 0; i < originalArray.length; i++)
{
int randNum = rand.nextInt(1000)+1;
originalArray[i] = randNum;
}
for(int i = 0; i < originalArray.length; i++)
{
System.out.println(i+"." + originalArray[i]);
}
System.out.println("---------------------End Random Array-------\n");
MergeSortAlgorithm.mergeSortAlg(originalArray);
int[] sortedArray = MergeSortAlgorithm.getSortedArray();
for(int i = 0; i < sortedArray.length; i++) //NULL POINTER EXCEPTION HERE
{
System.out.println(i+ "." + sortedArray[i]);
}
}
}
Algorithm Class:
public class MergeSortAlgorithm
{
private static int[] newArray;
public static void mergeSortAlg(int[] randomNums)
{
int size = randomNums.length;
if (size < 2)
{
return; //if the array can not be split up further, stop attempting to split.
}
int half = size / 2;
int firstHalfNums = half;
int secondHalfNums = size - half;
int[] firstArray = new int[firstHalfNums];
int[] secondArray = new int[secondHalfNums];
for (int i = 0; i < half; i++)
{
firstArray[i] = randomNums[i];
}
for (int i = half; i < size; i++)
{
secondArray[i - half] = randomNums[i];
}
mergeSortAlg(firstArray);
mergeSortAlg(secondArray);
merge(firstArray, secondArray, randomNums);
}
public static void merge(int[] firstArray, int[] secondArray, int[] newArray)
{
int firstHalfNums = firstArray.length;
int secondHalfNums = secondArray.length;
int i = 0; //iterator for firstArray
int j = 0; //iterator for second array
int k = 0; //interator for randomNums array
while (i < firstHalfNums && j < secondHalfNums)
{
if (firstArray[i] <= secondArray[j])
{
newArray[k] = firstArray[i];
i++;
k++;
}
else
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
while (i < firstHalfNums)
{
newArray[k] = firstArray[i];
k++;
i++;
}
while (j < firstHalfNums)
{
newArray[k] = secondArray[j];
k++;
j++;
}
}
public static int[] getSortedArray()
{
return newArray;
}
}
Basically, the only problem with your code is that you don't initialize newArray with any values, resulting in a null.
You are also redefining newArray at the top of your merge function .
The problem is that newArray[] is never instantiated i.e. newArray reference is pointing to null. And, no change is made in the newArray so value or reference returned to main is null. And, then you are performing sortedArray.length where sorted array having a null value.
You have to make newArray[] point to randomNums[].

Why does this code in java print a reference instead the result of invoking the method?

I am supposed to write a method that accepts 3 2-D arrays of This method should determine whether one of the matrices is the result of matrix addition of the other two.
public class Matrix {
public static void main(String[]args){
int [][] a = {{5,2,3},{4,1,6},{0,7,2}};
int [][] b = {{1,2,3},{4,5,6},{0,1,2}};
int [][] t = {{6,4,6},{8,6,12},{0,8,4}};
System.out.println(add(a,b));
System.out.println(check(a,b,t));
}
public static int [][] add(int[][]a,int[][]b){
int i=0;
int j=0;
int[][] r = new int [3][3];
while (i<a.length){
r[i][j] = a[i][j] + b[i][j];
i++;
j++;
}
return r;
}
public static boolean check(int[][]a,int[][]b,int[][]t){
int i = 0;
int j = 0;
while(i<t.length){
if(t==add(a,b))
return true;
}
return false;
}
}
add returns an array. Arrays in Java are objects, but they do not override the toString() method. When printing, you'd print their default toString() call, which is implemented by Object as return getClass().getName() + "#" + Integer.toHexString(hashCode());.
Luckily, Java provides a utility in the form of java.util.Arrays.deepToString(Ojbect[]) to generate a more readable string output:
System.out.println(Arrays.deepToString(add(a,b)));
EDIT:
Your add method is also wrong. Your code iterates i and j together, so it only sums the elements along the matrix's diagonal instead of adding all of them. You should use a nested loop instead:
public static int [][] add(int[][]a, int[][]b) {
int[][] r = new int [3][3];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
r[i][j] = a[i][j] + b[i][j];
}
}
return r;
}
Your check method, by the way, is also wrong - it attempts to compare the array itself instead of is elements:
public static boolean check(int[][]a, int[][]b, int[][]t) {
int[][] r = add(a, b);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (r[i][j] != t[i][j]) {
return false;
}
}
}
return true;
}

Categories