Printing 3D Array - java

I am trying to print arrays before and after they are filled with user given inputs. Therefore, this would be the output if the given size is 3:
//user inputs values for first matrix
Before adding:
Array [0] =
Array [1] =
Array [2] =
//add user inputs
After adding:
Array [0] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[1] = Array[2] =
//ask for inputs for second matrix
Before Adding
Array [0] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[1] = Array[2] =
After adding
Array [0] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[1] = row 0 = [...]
row 1 = [...]
... depending on user given size of the first matrix
Array[2] =
I wrote the following code to achieve this (In a class called ThreeDRayRunner):
public static void print(int [][][] array)
{
for (int i=0; i<array.length; i++ )
{
for (int x=0; x<array[i].length;x++)
{
System.out.println();
System.out.print("row "+ x);
for (int j=0; j<array[i][x].length;j++)
{
System.out.print (array[i][x][j]+ " ");
}
}
}
However,I get the following error:
Exception in thread "main" java.lang.NullPointerException
at ThreeDRay.print(ThreeDRay.java:13)
at ThreeDRayRunner.main(ThreeDRayRunner.java:41)
Also, in the runner I ask the user to input the integer that will be stored in the 3D Array. To do this I ask for the size and print the 3D Array when is empty and after the given numbers are added. This is my code for that:
Scanner keyboard = new Scanner(in);
out.print("How many matrices are you going to enter? ");
int s = keyboard.nextInt();
int[][][] d3= new int [s][][];
for(int i = 0; i < S; i++)
{
out.print("What is the size of the matrix " + i + " ? ");
int size = keyboard.nextInt();
int[][] mat = new int[size][size];
out.println();
for(int r=0; r<mat.length; r++)
{
for(int c=0; c<mat[r].length; c++)
{
out.print("Enter a value for spot " + r + " - " + c );
mat[r][c]=keyboard.nextInt();
}
}
out.println("The array before setting mat at spot "+i);
ThreeDRay.print(d3);
d3[i] = mat;
out.println("The array after setting mat at spot "+i);
ThreeDRay.print(d3);

You are not instantiating the 2nd and 3rd dimensions of d3 Did you mean to do this line before your first print?
d3[i] = mat;
So it would look like this:
d3[i] = mat;
out.println("The array before setting mat at spot "+i);
ThreeDRay.print(d3);
Follow up:
It looks like you actually didn't want to set d3[i] before your first print. In that case make sure you 3 dimensions for d3 are all non-null since your print is going to print all of them and not only the one that you set to mat. Initialize your 2nd and 3rd dimensions (to 0) before you start.
int[][][] d3= new int [s][][];
for (int i=0; i < d3.length ;++i){
d3[i] = new int[0][0];
}

Related

Solve the task. using 1 array

I wrote a small program.
Сondition: "Given an array of size n. Insert an element with a zero value after each negative element of the array." I solved this task using 2 ArrayList arrays. I'm wondering if it's possible to get a solution using only 1 array?
Code of the program:
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> ArrIntNum = new ArrayList<>(sizeArr); // Declare array
Random rnd = new Random();
int val;
// Filling array random elements from -20 to 20
for(int i = 0; i < sizeArr; i++){
val = -20 + rnd.nextInt(41);
ArrIntNum.add(i, val);
}
// Output array on the screen
System.out.println(ArrIntNum.toString());
ArrayList<Integer> ArrWithZeroAftNegVal = new ArrayList<>(); // Declare once more array
// Adding zero after every negative number in array ArrIntNum and write in array ArrWithZeroAftNegVal
for(int i = 0; i < sizeArr; i ++){
if(ArrIntNum.get(i) < 0) {
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
ArrWithZeroAftNegVal.add(0);
}
else
ArrWithZeroAftNegVal.add(ArrIntNum.get(i));
}
// Output edited array on the screen
System.out.println(ArrWithZeroAftNegVal.toString());
}
}
A ListIterator works quite naturally, allow addition of elements on the same array:
ListIterator<Integer> i = ArrIntNum.listIterator();
while (i.hasNext()) {
Integer value = i.next();
if (value < 0) i.add(0);
}
Like this:
import java.util.ArrayList;
public class Task_108 {
public void Task108(){
System.out.println("Input size of array: ");
Scanner scn = new Scanner(System.in);
int sizeArr = scn.nextInt();
ArrayList<Integer> arrIntNum = new ArrayList<Integer>(sizeArr); // Declare array
Random rnd = new Random();
// Filling array random elements from -20 to 20
for(int i = 0; i < arrIntNum.size(); i++)
arrIntNum.add(-20 + rnd.nextInt(41));
// Output array on the screen
System.out.println(arrIntNum);
// Adding zero after every negative number in array ArrIntNum
for(int i = 0; i < sizeArr; i++) {
if(arrIntNum.get(i) < 0)
arrIntNum.add(i + 1, 0);
}
// Output edited array on the screen
System.out.println(arrIntNum);
}
}
I also simplified your code for you.

User inputs doubles which get stored in an array. Array size is unknown and should grow dynamically

So I have an assignment where I take in doubles from the user in the console and then store those doubles in an array. These doubles will actually be coordinates which I will use later on.
The program should be able to take an unknown amount of doubles from the user. The problem I am having is allowing the array size to grow dynamically. We CANNOT use arrayList or any java library collection classes. Here is what i have so far:
import java.util.Scanner;
public class testMain{
public static void main(String[] args){
Scanner userInput = new Scanner(System.in);
boolean debug = true;
//Two array's where i'll store the coordinates
double[] coord1 = new double[3];
double[] coord2 = new double[3];
//Array for user commands
String[] commands = { "random", "exit", "help"};
for(int i = 0; i < coord1.length; i++){
System.out.println("Enter Coordinates: ");
double index = userInput.nextDouble();
//If more doubles needed for array we want to resize array
if(coord1[i] >= coord1.length){
for(int j = 0; j < 10; j++){
coord1[j] = j + 10;
}
double newItems[] = new double[20];
System.arraycopy(coord1, 0, newItems, 0 ,10);
coord1 = newItems;
}
coord1[i] = index;
}
if(debug == true){
printArray(coord1);
}
}
public static void printArray(double arr[]){
double n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
I can't seem to figure out how to recognize when the reaching the end of coord1 to execute code to increase the size and continue looping for more doubles.
Later on when the user is done an empty entry from console should exit loop and display the array.
Your problem is that you use a for loop, which is only looping over every element of your array. So, it will never give the user a chance to enter more elements than are in the array. Use a while loop so that instead of looping once for every element, you can loop until the user enters "exit".
Here is a slight modification of your code that should work:
Scanner userInput = new Scanner(System.in);
//Two array's where i'll store the coordinates
double[] coord1 = new double[3];
double[] coord2 = new double[3];
//Array for user commands
String[] commands = { "random", "exit", "help"};
System.out.println("Enter Coordinates: ");
String input = userInput.nextLine();
int arrayIndex = 0;
while (!input.equals("exit")) {
//convert input to a double
System.out.println("Enter Coordinates: ");
double userDouble = Double.parseDouble(input);
//handle case where array needs to be resized
if (arrayIndex >= coord1.length) {
double[] newCoord1 = new double[coord1.length * 2];
for (int copyIndex = 0; copyIndex < coord1.length; copyIndex++) {
newCoord1[copyIndex] = coord1[copyIndex];
}
coord1 = newCoord1;
}
//store the value
coord1[arrayIndex] = userDouble;
arrayIndex = arrayIndex + 1;
//take new input
input = userInput.nextLine();
}
Keep in mind that this doubles the array size when a resize is needed. That means that if the array size doubles to 6 and the user only enters 5 values, you will have a couple of empty values (zeros) at the end of your array. If that is a problem you can modify it.
You can use a while to loop until the command "exit" is typed by the user. here is an example of dynamically adding elements to the array before each item is added to the array.
String[] number;
String userInput = "";
String[] commands = { "random", "exit", "help"};
double[] coord1 = new double[0];
double[] coord2 = new double[0];
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter Coordinates (ex 1,3)\n");
userInput = scan.nextLine();
if(!userInput.equals(commands[1]))
{
number = userInput.split(",");
if(number.length != 2 || !number[0].matches("\\d+") || !number[1].matches("\\d+"))
{
System.out.println("Error: Invalid Input! Try again");
}
else
{
//our index to place our numbers will be the current length of our array
int index = coord1.length;
double[] temp = new double[coord1.length + 1];
//copy the content to the same array but just 1 size bigger
System.arraycopy(coord1, 0, temp, 0, coord1.length);
coord1 = temp;
temp = new double[coord2.length + 1];
System.arraycopy(coord2, 0, temp, 0, coord2.length);
coord2 = temp;
//now use our index to place the numbers in the correct locations
coord1[index] = Double.parseDouble(number[0]);
coord2[index] = Double.parseDouble(number[1]);
}
}
} while (!userInput.equals(commands[1]));
for(int i = 0; i < coord1.length; i++)
{
System.out.println(i + " - X: " + coord1[i] + " Y: " + coord2[i]);
}
Note I use comma seperated values to make the user's life and my life easier, allowing them to enter the coordinates at the same time.
Example output
Enter Coordinates (ex 1,3)
1,5
Enter Coordinates (ex 1,3)
4,7
Enter Coordinates (ex 1,3)
8,9
Enter Coordinates (ex 1,3)
gffd
Error: Invalid Input! Try again
Enter Coordinates (ex 1,3)
3 6
Error: Invalid Input! Try again
Enter Coordinates (ex 1,3)
0,0
Enter Coordinates (ex 1,3)
exit
0 - X: 1.0 Y: 5.0
1 - X: 4.0 Y: 7.0
2 - X: 8.0 Y: 9.0
3 - X: 0.0 Y: 0.0

Negative Arrays and Error Messages

//MY TASK IS TWO MERGE TO ARRAYS INTO ASCENDING ORDER.Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int one[]= new int[10000];
int two[]= new int[10000];
int lengthShort=0;
int lengthLong=0;
int a =0;
int b =0;
System.out.println("Enter the values for the first array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<one.length && scan.hasNext(); i++){
one[i] = scan.nextInt();
a++;
if(one[i]<0){
one[i]=0;
break;
}
}
int length1 = a-1;
System.out.println("Enter the values for the second array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<two.length && scan.hasNext(); i++){
two[i] = scan.nextInt();
b++;
if(two[i]<0){
two[i]=0;
break;
}
}
int lengthTwo = b-1;
int mergeOne[] = new int[length1];
for (int i = 0; i<mergeOne.length; i++){
mergeOne[i]=one[i];
}
int mergeTwo[] = new int[lengthTwo];
for (int i = 0; i<mergeTwo.length; i++){
mergeTwo[i]=two[i];
}
System.out.println("First Array:");
for(int i=0; i<mergeOne.length; i++){
System.out.print(mergeOne[i] + " ");
}
System.out.println("\nSecond Array:");
for(int i=0; i<mergeTwo.length; i++){
System.out.print(mergeTwo[i] + " ");
}
if(mergeOne.length<=mergeTwo.length){
lengthLong = mergeTwo.length;
lengthShort = mergeOne.length;
}
else if(mergeOne.length>=mergeTwo.length){
lengthShort = mergeTwo.length;
lengthLong = mergeOne.length;
}
int merged[] = new int[length1 + lengthTwo];
for(int i = 0; i<lengthShort; i++){
if(i==0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i] = mergeOne[i];
merged[i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i] = mergeTwo[i];
merged[i+1]= mergeOne[i];
}
}
else if(i>0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i+i] = mergeOne[i];
merged[i+i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i+i] = mergeTwo[i];
merged[i+i+1]= mergeOne[i];
}
}
}
if(mergeOne.length<mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeTwo[k];
}
}
if(mergeOne.length>mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeOne[k];
}
}
for(int i = 0; i<merged.length; i++){
if((i+1)==merged.length)
break;
if(merged[i]>merged[i+1]){
int temp = merged[i+1];
merged[i+1]=merged[i];
merged[i]= temp;
}
}
System.out.println("\nMerged array in order is: ");
for(int i = 0; i<merged.length; i++){
System.out.print(merged[i] + " ");
}
}
}
//My code compiles in drjava but I have two issues:
1) It doesn't order the numbers in ascending order
2) When I run it through the site I have to submit this on it gives me the message as follows:
Runtime Error
Exception in thread "main" java.lang.NegativeArraySizeException
at Main.main(Main.java:281)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
You'll need to rethink your merge algorithm. Suppose you input arrays are
1 5 10 50 100 500
2 4 6 8 10 12 14 16
You'll need to repeatedly decide which element is smaller to put into the output. So after selecting N elements, your output will look like
1 2 4 5 6 8 10 10 12 14
And you will need to have indexes pointing at the place in the input arrays you'll need to look at next:
1 5 10 50 100 500
^^
2 4 6 8 10 12 14 16
^^
As you can see, the indexes could be at very different places in the input arrays. However, your code does a lot of this:
if(mergeOne[i]<=mergeTwo[i]){
which means it's only comparing elements from the input that are in the same location. This doesn't work, and trying to swap elements in the output after the fact isn't good enough to get the job done.
Basically, instead of having one index and comparing the elements of the two input arrays at the same index, you'll need two indexes. I'll let you take it from there, but I think you can figure it out.
(And I have no idea why you're getting NegativeArraySizeException.)

finding the value in 2D array by inputting address

I am trying to get the String right after the position i input, but it is not working and i can not identify why.
This is my code.
import java.util.*;
public class LabTest1_Mardi {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
String myArray [][] = { {"a","b"}, {"c","d"}, {"e","f"}, {"g","h"}};
//Getting row and cols
int rows = myArray.length;
int cols = myArray[0].length;
System.out.println("Rows = "+rows+" Cols = "+cols);
for (int x=0;x<rows;x++){
for (int y =0;y<cols;y++){
System.out.println("array "+x+" " + y + " : = "+myArray[x][y]);
}
}
System.out.println("Enter Possition row : ");
int posR = input.nextInt();
System.out.println("Enter Possition col : ");
int posC = input.nextInt();
System.out.println(myArray[posR+1][posC+1]);
input.close();
}
}
Which position are you trying to get? For example, if you enter in 0,0 (a) do you want b (0,1) or c (1,0)? Right now it should return d (1,1) because both row and column are incremented.
Image your 2D array looks like this,
0 , 1
0: a , b
1: c , d
2: e , f
3: g , h
Right now you're shifting both row and column, make sure that's exactly what you want to do. Also you'll get an error if the user enters a 1 as their input values.

Strange output when printing array [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I'm using this code:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Matrix
{
public static void main(String[] args)
{
Scanner enter = new Scanner(System.in);
int[][] firstMatrix = new int[4][4];
int[][] secondMatrix = new int[4][4];
Random spin = new Random();
System.out.println("Please enter 16 numbers to populate the array: ");
for (int count = 0; count<firstMatrix.length;count++) // nested for for user input to populate 4x4 array
{
for (int count2 = 0; count2 < firstMatrix[count].length; count2++)
{
firstMatrix[count][count2] = enter.nextInt(); // populate array with user input
}
} // end array population
System.out.printf("The sum is: %d%n", sumMatrix(firstMatrix)); // call sumMatrix
System.out.println(firstMatrix[0][0]); // debug
for (int count3 = 0; count3<secondMatrix.length; count3++) // nested for to populate array with random numbers 1-100, row
{
for (int count4 = 0; count4<secondMatrix[count3].length; count4++) // column
{
secondMatrix[count3][count4] = 1 + spin.nextInt(100); // 100 inclusive, generate and populate array
}
}
System.out.println(secondMatrix[0][0]); // debug to show that it is properly printing the correct element
for (int i = 0; i<secondMatrix.length; i++)
{
for (int j = 0; j<secondMatrix[i].length; j++)
System.out.print(" " + secondMatrix[i][j]); // print the total array ( this process can be used to print the returned array )
}
System.out.println(); // debug
int arrayTotal = firstMatrix[0][0] + secondMatrix[0][0]; // debug
System.out.println("The element total is " + arrayTotal); // debug
System.out.println();
addMatrix(firstMatrix,secondMatrix); // call addMatrix
System.out.println("Programmed by Stephen Mills");
} // end main
public static int sumMatrix(int[][] array) // method to sum the elements of the array
{
int total = 0;
for (int number = 0; number<array.length; number++) // row
{
for (int number2 = 0; number2<array[number].length; number2++) // column
total += array[number][number2]; // sum of all elements
}
return total; // returns the sum
} // end sumMatrix
public static int[][] addMatrix(int[][] array1, int[][] array2) // improper method
{
int[][] thirdMatrix = new int[4][4];
for (int count4 = 0; count4<thirdMatrix.length; count4++)
{
for (int count5 = 0; count5<thirdMatrix[count4].length; count5++)
thirdMatrix[count4][count5] = array1[count4][count5]+array2[count4][count5];
}
System.out.println(Arrays.toString(thirdMatrix));
return thirdMatrix;
} // end addMatrix7
}
Most of the program works as intended but I'm getting this "[[I#3d4eac69, [I#42a57993, [I#75b84c92, [I#6bc7c054" output when trying to print my array. I've tried several methods, including simple println, toString, setting a variable equal to the method call, and I've tried putting the print statement in main first and then in the method second. Any ideas why this is happening?
If you want to print int elements of the 2d array thirdMatrix you can try this:
for(int[] simpleArray: thirdMatrix)
System.out.println(Arrays.toString(simpleArray));
The reason of your output: when you call
Arrays.toString(thirdMatrix)
you will call
String.valueOf(element)
foreach element of thirdMatrix. As elements of thirdMatrix are Array not primitive types, method
String.valueOf(Object obj)
will be called which return the hashcode of thirdMatrix elements(one-dimensional arrays).

Categories

Resources