Java - Printing 2d array with (with spaces between lines) [duplicate] - java

This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 7 years ago.
I have a basic java question - I have an array and I need to do a multiplication of all the elements, so for input:
1 2 3
The output will be:
1 2 3
2 4 8
3 6 9
How can I print the 2d array from the main ?
PS - I want the method just to return the new 2d array, without printing it ( I know I can do it without the method and and print mat[i][j] within the nested loop)
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3};
System.out.println(matrix(array));
}
public static int[][] matrix(int[] array){
int[][] mat = new int[array.length][array.length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
mat[i][j] = array[i] * array[j];
}
}
return mat;
}
}

You have to print all the individual elements of the array, because if you just try to print an array, it will print all kinds of other stuff you might not want to see. So you cherry pick out what you want, and format it a little. In the below code you have each element printed, seperated on a space until it reaches a new row, where it then jumps to a new line.
int[][] matrixArray = matrix(array);
for(int i = 0, i < matrixArray.length; i++) {
for(int j = 0; j < matrixArray[0].length; j++) {
System.out.print(matrixArray[i][j] + " ");
}
System.out.println();
}

Related

Printing Stack of Arrays [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Some operation is performed on an array in function fillStackWithArray() and after the operation the array is pushed into the stack and is repeated again.
But the issue occurs when I try to print the stack. It gives me wrong answer.
Output:
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
Expected Output:
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
Code:
import java.util.Stack;
public class ArraysOnStack {
public static void main(String[] args) {
int sizeOfArray = 5;
Stack<int[]> stack = fillStackWithArray(5);
printStack(stack);
}
private static void printStack(Stack<int[]> stack) {
while (!stack.empty()) {
int[] arr = stack.pop();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
private static Stack<int[]> fillStackWithArray (int size) {
Stack<int[]> stack = new Stack<>();
int[] arr = new int[size];
// Some Operation that fills Stack with Arrays.
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[j] = size - i;
}
// Pushing the array into stack on which some operation
// is performed.
stack.push(arr);
}
return stack;
}
}
PS: The operation is random to just fill the array. But my question is related to such a situation.
Try this.
private static Stack<int[]> fillStackWithArray (int size) {
Stack<int[]> stack = new Stack<>();
int[] arr = new int[size];
// Some Operation that fills Stack with Arrays.
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[j] = i + 1; // changed
}
// Pushing the array into stack on which some operation
// is performed.
stack.push(arr.clone()); // changed
}
return stack;
}
output
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
You are pushing same int[] in stack in fillStackWithArray. An int array in Java is a subclass of Object, therefore it's an object type. Create int[] array inside loop.
for (int i = 0; i < size; i++) {
int[] arr = new int[size];
...
}
The int[] being pushed onto the stack is initialized once outside the loop. The same array is being updated in subsequent iterations. You need to declare the int[] array inside the loop.
The value assigned to the variable i should begin from 1 to i <= size since the output needs to be printed from 5 to 1 and as a Stack is being used, the insertion order needs to be reversed as the first element that is pushed will be printed last. Hence, the value assigned to arr[j] should be i.
for (int i = 1; i <= size; i++) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = i;
}
// Pushing the array into stack on which some operation
// is performed.
stack.push(arr);
}
In the fillStackWithArray() function you have created a single array arr and you are changing the same arr in each iteration.
To fix this, create a new array for each iteration of the outer loop.
To understand the issue, read about deep-copy and passing by reference.

How to print an 2d array of Char (JAVA) [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
I am trying to print out a gameBoard that has a "-" for each spot of the array: however every time I run this code I get this printed to the console:
[[C#2a139a55.
Any suggestions?
public class Game {
public static void main(String[] args){
char realBoard[][] = new char[7][7];
for (int i=0;i<7;i++){
for(int j=0;j<7;j++){
realBoard[i][j]='-';
}
}
System.out.print((realBoard));
}
}
realBoard is an array, an object, so you can't just print it like that. You will need to iterate over the elements again
for(char[] y: realBoard) {
for(char x: realBoard) {
System.out.print(x);
}
System.out.println();
}
Unless you need to use the array data of mark elsewhere, you would be better off just using print statements inside your loops.
for(int i = 0; i < 7; i++) {
for(int j = 0; j < 7; j++) {
//Print for each row
System.out.print("-");
}
//Move to next line
System.out.print("\n");
}
You can't print a 2D array like that. To print a 2D array in one line you can use:
System.out.println(Arrays.deepToString(realBoard));
Or in multiple lines:
for(char[] x: realBoard)
System.out.println(Arrays.toString(x));
Credits: Java - Best way to print 2D array?

How to Fix Spanish Numbers

What I have to do is to create a SpanishNumbers application that displays numbers 1 through 10 in Spanish. A method with an int parameter should display the Spanish word for the number passed. A loop structure in the main() method should be used to call the method ten times. The Spanish word equivalents for numbers 1 through 10 are...
1 uno 2 dos, 3 tres, 4 cuatro, 5 cinco, 6 seis, 7 siete, 8 ocho, 9 nueve, 10 diez.
I do not know why am I getting this error below
http://i.stack.imgur.com/HLIiI.png
Thanks in advanced!
import java.util.Scanner;
public class SpanishNumberss {
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
}
public static void main(String args[]) {
for (int i = 1; i <= 10; i++)
spanishNumbers(i);
}
}
In Java, indexes of an array start with 0, not 1, and run through length - 1, not length.
Adjust your for loop condition in main as follows:
for (int i = 0; i < numbers.length; i++)
You'll need to adjust your other for loop similarly.
Arrays indexes are 0 based (starts from 0 not from 1) . Also you are declaring your array numbers inside the method each time is called just declare as a class variable. So take care that in your example index 0 refers to 1 (uno) and so on.
I made you an example and add 0,"cero"
public class SpanishNumberss {
private static final String[] numbers = {"cero","uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
public static void spanishNumbers(int num) {
//loop here is unnecesary
System.out.println(numbers[num]);
}
public static void main(String args[]) {
//and here in main i call them from 1 to 10
for (int i = 1; i < 11; i++){
spanishNumbers(i);
}
}
}
ArrayIndexOutOfBounds means you have gone out of the boundaries of your array (in your case numbers). What you have to realize is array's are 0 index-based. So in your for loop, you really 0 - 9, not 1-10.
And an even better solution, as #rgettman has posted is to use the length property of the array. So you are not hard-coding in those magic numbers.
Arrays go from 0 to N-1
That's why you're getting that error, change your for cycle to:
for (int i = 1; i <= num; i++) {
System.out.println(numbers[num]);
}
Your problem is here:
for (int i = 1; i <= num; i++)
Arrays in Java are 0-based. So the valid indices run from 0 to array.length - 1. So an array of length 5 would have the valid indices 0, 1, 2, 3, and 4. Change your loop to the following:
for (int i = 0; i < num; i++)
This will ensure that in your loop i will only have the values from 0 to 9.
your loop should only have the values from 0 to 9:
for (int i = 0; i < num; i++)
first of all i don't think you need a loop in the spanishnumber method...
cos you already know the index of what you are looking...// that's if i understand you
so the only place you need the loop is in the main method...so your code should look like dis
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
spanishNumbers(6);
}
}
public static void spanishNumbers(int num) {
String[] numbers = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez"};
System.out.println(numbers[num -1]);
}

I keep receiving a .class expected error [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 2 years ago.
Here is what I'm supposed to do:
Write a program to read a 2-D array of 4x4. Then read the first element of the array and compare it with the third element of each column. Replace the smaller value with the larger values of the two. Create a method called swap to swap the values.
I'm not sure what I'm doing wrong and I'm just starting to learn arrays. My teacher is very conceptual and isn't very concrete on his definition so I'm having trouble with it. I keep receiving a .class expected error.
public class Array {
public static void main(String[] args) {
int num [][] = {{4, 6, 7, 2},
{5, 12, 9, 8},
{1, 0, 3, 10},
{5, 3, 14, 11}};
System.out.println("the array elements are:");
for(int i = 0; i < num.length; i++){
System.out.println();
for(int j = 0; j < num[i].length; j++)
System.out.print(num[i][j] + " ");
}
System.out.println("swaped elements are:");
for(int i = 0; i < num.length; i++){
System.out.println();
for(int j = 0; j < num[i].length; j++)
System.out.print(swap(num[][]) + " ");
}
}
public static void swap (int x[][]){
for(int i = 0; i < x.length; i++){
int temp = x[0][i];
if (x[0][i] > x[2][i] ){
x[2][i] = temp;
x[0][i] = x[2][i];
}
}
}
}
swap() doesn't return anything. Even if you did resolve the other issue (num[][] is a syntax error), you'd need to specify something to return from swap. Hint: probably the array you modified.
Write a program to read a 2-D array of 4x4.
I don't see you reading something. Just initializing it. Maybe you should read from stdin or from a file?
Then read the first element of the array and compare it with the third element of each column.
Replace the smaller value with the larger values of the two.
Create a method called swap to swap the values
As a swap method I would expect a method with 4 indexes for the 2 positions in the 2D-Array, where the values to swap are located.
public static void swap (int x[][], int i1, int i2, int j1, int j2) {
int temp = x[i1][j1];
x[i1][j1] = x[i2][j2];
x[i2][j2] = temp;
}
Have you heard about the simplified for-loop?
public static void show (int x[][]) {
for (int [] inner : x)
for (int i : inner)
System.out.print (i + " ");
}

Reversing elements of an array

Given an array a and two other int variables, k and temp, write a loop that reverses the elements of the array.
for (k = 0; k < a.length-1; k++) {
temp = a[k];
a[k] = a[a.length-1-k];
a[a.length-1-k] = temp;
}
This is not working. Any idea why?
E.g., for a = [0, 1, 2, 3, 4, 5] you'll switch 0 and 5 twice: when i == 0 and when i == 5. This double-switching will put both elements into their original positions: (0, 5) -> (5, 0) -> (0, 5).
Try to make your loop to go through half of array only: so each pair is switched once.
You need to stop your loop at a.length/2 (in the middle).
for(k=0;k<a.length/2;k++)
This should work for odd and even length arrays if this is integer division.
check this at my blog hope this going to help http://codeheaven.wordpress.com/
Here is the code from above link:
public class ArrayReversing {
public static void main(String a[]){
int arr[]={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int temp;
int as = arr.length;
int k = as – 1;
System.out.println(“Array Before Reversing”);
printArray(arr);//method used to print array on screen
ArrayReverse://using loops with title
for(int i = 0; i < arr.length/2 ; i++){
temp = arr[k];// swaping
arr[k] = arr[i];
arr[i] = temp;
k–;
}
System.out.println(“Array After Reversing”);
printArray(arr); // calling the method printArray to print the elements of array
}
static void printArray(int ar[]){
PrintArray:
for(int l:ar)
System.out.println(l);
}
}
Output:
Array Before Reversing
1
2
3
4
5
6
7
8
Array After Reversing
8
7
6
5
4
3
2
1
Use a Stack. A stack reverses the elements that are added to it. A stack can be described as First In, Last Out (FILO). "Push" adds the elements to the stack and "Pop" removes them.
public static int[] num1 = {1,2,3,4,5,6};
public static Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
for(int i = 0; i < num1.length; i++){
stack.push(num1[i]);
}
for(int i = 0; i < num1.length; i++){
System.out.print(stack.pop());
}
}
Output:
654321
You are swapping elements from each end of the array... and iterating to the items you've already swapped... is that enough of a hint?
You might also want to look at the ArrayUtils.reverse method.
Here is an example using that method.
I know you cannot use it in this assignment. But you should be aware of this and use it whenever possible, say in your assignments, projects.
This will work
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}
Try this will simply work:
public class ReverseArray{
public static void main(String[] args){
int[] a ={1,2,3,4,5};
for(int i=a.length-1;i>=0;i--){
System.out.print(a[i]);
}
}
}

Categories

Resources