How to print an array that was inputted from Scanner? [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
So I have an array and trying to print what was input to the scanner. I'm trying to print the matrix that was input. Heres the code, what am I doing wrong here? I tried to print just graph, doesn't work.
/** Accept number of vertices **/
System.out.println("Enter number of vertices\n");
int V = input.nextInt();
/** get graph **/
System.out.println("\nEnter matrix\n");
int[][] graph = new int[V][V];
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph[i][j] = input.nextInt();
System.out.print(graph);

Printing arrays by simply passing it into System.out.print will print the array's hashcode. See this.
What you want to do is: System.out.println(Arrays.deepToString(graph));
Arrays.toString(...) will work for single dimensional arrays.
Arrays.deepToString(...) will work for more complex arrays.

Because when you try to print graph, you are actually printing a reference to an array object (If I am correct).
Also, for variables (like "V") you should use small caps
Instead of printing a graph, do this:
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
System.out.print(graph[i][j]);
}
System.out.println();
}

You can print the contents of an array using the Arrays.toString() method but it doesn't work for multidimensional arrays, so for a 2 dimensional array, you'll need to loop through the elements in the first dimension. Like this:
for (int[] g : graph) {
System.out.println(Arrays.toString(g));
}

Related

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?

Java Printing Array based off Another Array

I am trying to print an Array, however, I am needing to print the right array, off of an integer from another array.
(i.e.) arrayInt contains 2,4,6,5,1. I want to use a for loop to print the numbers. Then, I want to print the double that is corresponding to the int. arrayInt, that has been sorted, is 1,2,3,4,5 and arrayDouble, that hasn't been sorted, is 2.6,6.9,1.3,2.4,9.8. After I print arrayInt[0], which is 1, I want to print the corresponding (in this case the 1st) value in arrayDouble.
The following code is what I came up with:
for (int k = 0; k < 7; k++)
System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[(sortedNum[k])]);
I think you kinda answered your own question here, have you tried the code that you specified?
If I understood correctly you want to print something from an array based on the index that is stored in another array, if so, the following code should work (notice I removed the parenthesees from your code):
for (int k = 0; k < 7; k++) {
System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[sortedNum[k]]);
}
This is assuming sortedNum is an array of ints and arrayWeight is an array of floats.
You have to check size of second array before trying to fetch value from it
for (int k = 0; k < 7; k++) {
if (sortedNum[k] < arrayWeight.length)
System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[sortedNum[k]]);
}

User input numbers into a 2 dimensional array in java

I'm having trouble with user input in java, hope anyone can help :)
The user declares how big the 2d array will be(number d is the side of the square array), then inputs a number "n", which tells the program how many inputs of numbers there will be, and then needs to input these numbers (eg. if n=4, the input must be sth like : 5 17 3 20.
I have already written the same thing for a single row array
for(i=0;i<=n;i++) {
arr[i]=sc.nextInt();
}
but am having trouble doing basically the same for the 2d array.
Any ideas?
Use two nested loops and index like arr[i][j]
int d=sc.nextInt(); //length of rows and columns
int n=sc.nextInt(); //user input how many numbers
int[][] array=new int[d][d]; //length and heigth of array
for (int i=0;i<d;i++) {
for(int j=0;j<d;j++) {
array[i][j]=sc.nextInt();
}
}
int distance=0;
int c=0;
for(int i=0;i<d;i++){
for(int j=0;j<d;j++){
array[i][j]=c;
c++;
}
}
that in the end is sth else, I just wanted for the whole thing to be seen, if maybe I missed something elsewhere.
Sorry I don't have the ability to comment yet so I am posting this as an answer. Essentially you need to use a nested for loop as stated above. I will provide you a basic template
for (int i = 0; i < length; i ++){
for (int j = 0; j < width; j ++){
if (counter < userInput){
counter++;
arr[i][j] = value;
} else {
break;
}
}
}

Multidimensional Arrays lengths in Java

How to find the lengths of a multidimensional array with non equal indices?
For example, I have int[][] pathList = new int[6][4]
Without actually hard-coding the indices, I need to find the '6' and the '4'.
I can find the 6 with pathList.length, but how to obtain the '4'?
This will give you the length of the array at index i
pathList[i].length
It's important to note that unlike C or C++, the length of the elements of a two-dimensional array in Java need not be equal. For example, when pathList is instantiated equal to new int[6][], it can hold 6 int [] instances, each of which can be a different length.
So when you create arrays the way you've shown in your question, you may as well do
pathList[0].length
since you know that they all have the same length. In the other cases, you need to define, specific to your application exactly what the length of the second dimension means - it might be the maximum of the lengths all the elements, or perhaps the minimum. In most cases, you'll need to iterate over all elements and read their lengths to make a decision:
for(int i = 0; i < pathList.length; i++)
{
int currLen = pathList[i].length;
}
This is for a 3 dimensional array.
int x[][][]=new int[5][8][10];
System.out.println(x.length+" "+x[1].length+" "+x[0][1].length);
OUTPUT :
5 8 10
Java has "jagged" multidimensional arrays, which means that each "row" in your two-dimensional array can have a different number of components. If you can assume that each row has the same number of components, use:
pathList[0].length;
Otherwise, you will have to iterate:
int maxRowLength = 0;
for (int i = 0; i < pathList.length; i++) {
if (maxRowLength < pathList[i].length) {
maxRowLength = pathList[i].length;
}
}
For 2 D array :-
int x[][] = new int[6][12];
System.out.println(x.length + " " + x[1].length);
OUTPUT : 6 12
pathList.length gives you the number of rows. This means it will output 6 for int[6][4]
pathList[i].length gives you the number of columns in the ith row. Since int[6][4] can be seen as a rectangle it will always output 4.
In java we can define array of arrays which we call multi dimensional arrays.By array of arrays we mean that a single elment of our array is again an array (in java can be of multiple length).To find length of multi array having all subarray of same size,we can use:
int[][]a=new int[3][3];//let a[][] be my array
a.length will work. //a is an object of proxy class and length is its property.
However,if you have subarrays of different sizes then you have to iterate it.
for(i=0;i<a.length;i++)
int cur_size=a[i].length;
In Java we can't use Length field like we used to one-dimensional arrays.
So simply writing a few lines of code solves this problem.
First, you need to know that the output of the Length field in multidimensional arrays is the number of rows.I mean when you have below array
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
the result of
System.out.println(numbers.length);
is 2, because you have 2 rows. So, you should use this to solve this problem.
Example:
public class Main {
public static void main(String[] args) {
//Array definition
int[][] numbers = {{1,2,3,4,2,6},{4,5,6,7}};
//Number of array's elements
int result = 0;
//calculate via loop
for(int i=0; i< numbers.length; i++){
result += numbers[i].length;
}
//output
System.out.println(result);
}
}
You can find '4' by using pathlist[i].length
Please rectify me if I am wrong as I am a novice and would help me in understanding Java better. The following code may help you in understanding.
public class Main {
public static void main(String[] args) {
int num[][] = new int[1][3];
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num[i].length; j++) {
num[i][j] = 10;
System.out.println("num [" + i + "] [" + j + "] = " + num[i][j]);
}
}
}
}
3-D array length
int[][][] a = new int[2][3][7];
int length=0;
for(int[][] i:a){
for(int j[]:i){
length+=j.length;
}
}
System.out.println(length);

Searching specific rows in a multi-dimensional array

I'm new to java programming and I can't wrap my head around one final question in one of my assignments.
We were told to create a static method that would search a 2-D array and compare the numbers of the 2-D array to an input number...so like this:
private static int[] searchArray(int[][] num, int N){
Now, the part what we're returning is a new one-dimensional array telling the index of the first number in each row that is bigger than the parameter variable N. If no number is bigger than N, then a -1 is returned for that position of the array.
So for example a multi-dimensional array named "A":
4 5 6
8 3 1
7 8 9
2 0 4
If we used this method and did searchArray(A, 5) the answer would be "{2,0,0,-1)"
Here is a very good explanation about Java 2D arrays
int num[][] = {{4,5,6},{8,3,1},{7,8,9}};
int N = 5;
int result[] = new int[num.length];
for(int i=0; i<num.length; i++){
result[i] = -1;
for(int j=0; j<num[0].length; j++){
if( N < num[i][j] ){
result[i] = j;
break;
}
}
}
for(int i=0; i<result.length; i++){
System.out.println(result[i]);
}
The first for loop(The one with a for inside it) traverses the 2D array from top to bottom
in a left to right direction. This is, first it goes with the 4 then 5,6,8,3,1,7,8,9.
First the result array is created. The length depends of the number of rows of num.
result[i] is set to -1 in case there are no numbers bigger than N.
if a number bigger than N is found the column index is saved result[i] = j and a break is used to exit the for loop since we just want to find the index of the first number greater than N.
The last for loop just prints the result.
Generally when using multi-dimensional arrays you are going to use a nested for loop:
for(int i = 0; i < outerArray.length; i++){
//this loop searches through each row
for(int j = 0; j < innerArrays.length; j++) {
//this loop searches through each column in a given row
//do your logic code here
}
}
I won't give you more than the basic structure, as you need to understand the question; you'll be encountering such structures a lot in the future, but this should get you started.

Categories

Resources