Whats wrong with this array? - java

public class lab {
public static void main (String args[]){
double[][] g = {RandomArray(3)};
printArray(g);
}
private static void printArray(double[][] g) {
System.out.println(Arrays.deepToString(g));
}
public static double[][] RandomArray(int n) {
double[] [] RandomArray = new double[n] [n];
Random randomNumberCreator = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
}
}
return RandomArray;
}
}
I am not sure what is wrong with my RandomArray method, i want it to work for 2-dimensional arrays but i have clearly made a mistake as the line below is receiving an error and I am unsure as to why this is happening. If you could explain to me the error that I have made i would be grateful.
double[][] g = {RandomArray(3)};

remove the curly brace around the function Call of "RandomArray"
public static void main (String args[]){
double[][] g = RandomArray(3);
printArray(g);
}
private static void printArray(double[][] g) {
System.out.println(Arrays.deepToString(g));
}
public static double[][] RandomArray(int n) {
double[] [] RandomArray = new double[n] [n];
Random randomNumberCreator = new Random();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
RandomArray[i][j] = randomNumberCreator.nextDouble() * 100;
}
}
return RandomArray;
}

You are initializing the array incorrectly....
you dont need the { } when calling the method RandomArray
just doing double[][] g = RandomArray(3); will do the job

Related

How can I print out array from a method in main?

I created a method that fills an array with prime numbers. However, I am struggling to understand how can I return it after it has been filled to the main method to print it? Returning like this gives me an error that it cannot find such a symbol.
public static int[] fillArray(int a) {
int[] arr = new int[a];
int m = 0;
for (int i = 1; m < arr.length; i++) {
if (isPrime(i)) {
arr[m] = i;
m++;
}
}
return arr;
}
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(arr);
}
I would suggest, you can do something like below,
public static int[] fillArray(int a){
int[] arr = new int[a];
int m = 0;
for (int i = 1; m < arr.length; i++){
if (isPrime(i)){
arr[m] = i;
m++;
}
}
return arr;
}
public static void main(String[] args) {
int a = Integer.parseInt("5"); //Pass a hard coded value or Read it from Scanner class and pass the same as argument
int[] arr = fillArray(a);
System.out.println(arr); //This line not actually prints the values of array instead it prints the Object representation of the array
// Below small piece of code will print the values of the array
for(int val:arr){
System.out.println(val);
}
}
public static int[] fillArray(int a){
int[] arr = new int[a];
int m = 0;
for (int i = 1; m < arr.length; i++){
if (isPrime(i)){
arr[m] = i;
m++;
}
}
return arr;
}
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int[] arr = fillArray(a); // This line was missing
System.out.println(Arrays.toString(arr));
}
Learn more about calling methods here: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

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;
}
}

displaying matrice double int java

I have a program in java and I got some problems with displaying on the console a result of a matrice int[] []. My code for the class matrice:
public class Matrix_complexSync {
private int m;
private int n;
private int[][] matrix1;
private int[][] matrix2;
private int[][] matrix3;
private int[][] tempResult;
private int[] counter;
private int firstNoThreads;
private int secondNoThreads;
public Matrix_complexSync(int m, int n) {
this.m = m;
this.n = n;
matrix1 = new int[m][n];
matrix2 = new int[m][n];
matrix3 = new int[m][n];
tempResult = new int[m][n];
counter = new int[m];
}
public void initialiseMatrix(int maxValue, int firstNoThreads, int secondNoThreads) {
Random randomGenerator = new Random();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix1[i][j] = randomGenerator.nextInt(maxValue);
matrix2[i][j] = randomGenerator.nextInt(maxValue);
matrix3[i][j] = randomGenerator.nextInt(maxValue);
}
}
this.firstNoThreads = firstNoThreads;
this.secondNoThreads = secondNoThreads;
}
public int[][] matrixMultiplicationLineThread() throws InterruptedException {
// my code
return tempResult;
}
}
and the main:
public static void main(String[] args) throws InterruptedException{
Matrix_complexSync m = new Matrix_complexSync(2,2);
m.initialiseMatrix(5, 1,1);
int res[][] = m.matrixMultiplicationLineThread();
System.out.println("The result is : " + Arrays.toString(res));
}
and the console shows me:
The result is : [[I#5fd0d5ae, [I#2d98a335]
Any ideas please to display the matrice in the good form?
for (int[] row : res)
{
System.out.println(Arrays.toString(row));
}

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;
}
}

Enum Type 2Darray maze

I am making a maze game with enumerated types to hold the values of walls, open spaces (etc) and i am not sure why this code does not work, i am trying to create a new board and set everything to open, then go through and randomly set values to the spots in the array.
maze = new Cell[row][col];
for (int r = 0; r < maze.length; r++) {
for (int c = 0; c < maze.length; c++)
maze[r][c].setType(CellType.OPEN);
}
Random randomMaze = new Random();
for (int ran = 0; ran <= numWalls ; ran++){
maze[randomMaze.nextInt(maze.length)][randomMaze.nextInt(maze.length)].setType(CellType.WALL);
}
this will do what you said. not sure you will get the kind of maze you want:
import java.util.Random;
class Maze {
enum CellType {
open,wall;
}
Maze(int n) {
this.n=n;
maze=new CellType[n][n];
init();
}
private void init() {
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
maze[i][j]=CellType.open;
}
void randomize(int walls) {
init();
Random random=new Random();
for(int i=0;i<=walls;i++)
maze[random.nextInt(n)][random.nextInt(n)]=CellType.wall;
}
public String toString() {
StringBuffer sb=new StringBuffer();
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++)
switch(maze[i][j]) {
case open:
sb.append(' ');
break;
case wall:
sb.append('|');
break;
}
sb.append('\n');
}
return sb.toString();
}
final int n;
CellType[][] maze;
}
public class Main {
public static void main(String[] args) {
Maze maze=new Maze(5);
System.out.println(maze);
maze.randomize(4);
System.out.println(maze);
}
}
I think, your inner loop should be something like
for (int c = 0; c < maze[r].length; c++)
... with the [r].
I have not tried it though.
I think that your maze would be a good candidate for a class. Something like this should work:
import java.util.Random;
public class Maze {
private int[][] mMaze;
private int mRows;
private int mCols;
//enums here:
public static int CELL_TYPE_OPEN = 0;
public static int CELL_TYPE_WALL = 1;
public Maze(int rows, int cols){
mRows = rows;
mCols = cols;
mMaze = new int[mRows][mCols];
for (int r = 0; r < mRows; r++) {
for (int c = 0; c < mCols; c++) {
mMaze[r][c] = Maze.CELL_TYPE_OPEN;
}
}
}
public void RandomizeMaze(int numWalls){
Random randomMaze = new Random();
for (int ran = 0; ran <= numWalls ; ran++){
mMaze[randomMaze.nextInt(mRows)][randomMaze.nextInt(mCols)]=(Maze.CELL_TYPE_WALL);
}
}
}

Categories