I'm trying to print all the elements in an array in a new line.
however when I'm trying to print, it comes up like this: (example)
array = [1,2,3,4];
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
prints:
1,
1,2,
1,2,3,
1,2,3,4,
How do I fix it?
However when I'm trying to print, it comes up like this
No, it doesn't. Your code hardly matches the output you're giving. You make an array by [] instead of {}, and you're output gives a ,, which is nowhere to be seen in your code.
The Output you're mentioning is incorrect, the code runs as it should, producing output :
1
2
3
4
Runs here
User Arrays.toString
int[] array = {1,2,3,4};
System.out.println(Arrays.toString(array));
this answers your specific question:
int[] array = {1,2,3,4};
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
System.out.print(" ");
}
Related
I was trying to take three command line arguments as input and do some basic maths operations, but the compiler is showing arrayindex out of bound error in lines having Interger.parseInt().
public class testarray {
public static void main(String args[]) {
int i=0;
int length,start,increament;
/*trying to take 3 command line arguments */
length=Integer.parseInt(args[0]);
int array[]=new int[length];
start=Integer.parseInt(args[1]);
increament=Integer.parseInt(args[2]);
if(args.length!=3) {
System.out.println("error");
}
else
{
for( i=0;i<array.length;i++) {
array[i]=start+(start+increament);
}
System.out.printf("%5d%8d\n","index", "value");
for(i=0;i<=array.length;i++) {
System.out.printf("%d%d\n",i,array[i]);
}
}
}
}
In last for loop in your program you have:
for(i=0; i <= array.length; i++)
It should be changed to
for(i=0; i < array.length; i++)
Also I would suggest to check if you pass the arguments the right way (especially when using IDE you have to pass them the way your IDE requires it), because if they are not read correctly it may cause ArrayIndexOutOfBoundsException in your program. I suggest you to firstly print content of arrays to check if they are correctly filled with data you desired to store in them just to make sure everything is done properly.
As you are trying to take three command line arguments then :
array.length = 3 , where indexes run from 0 , 1 and 2.
In last for loop of your program you have :
for(i=0; i <= array.length; i++)
Now , for i = 3 we have 3 <= array.length as true and when you try to access
array[3] in your for loop exception is raised . In order to avoid it
change follow
for(i=0; i < array.length; i++)
I have a string array
"Ben", "Jim", "Ken"
how can I print the above array 3 times to look like this:
"Ben", "Jim", "Ken"
"Jim", "Ben", "Ken"
"Ken", "Jim", "Ben"
I just want each item in the initial array to appear as the first element. The order the other items appear does not matter.
more examples
Input
"a","b","c","d"
output
"a","b","c","d"
"b","a","c","d"
"c","b","a","d"
"d","a","c","d"
Method signature
public void printArray(String[] s){
}
Rather than give you straight-up code, I'm going to try and explain the theory/mathematics for this problem.
The two easiest ways I can come up with to solve this problem is to either
Cycle through all the elements
Pick an element and list the rest
The first method would require you to iterate through the indices and then iterate through all the elements in the array and loop back to the beginning when necessary, terminating when you return to the original element.
The second method would require you to iterate through the indices, print original element, then proceed to iterate through the array from the beginning, skipping the original element.
As you can see, both these methods require two loops (as you are iterating through the array twice)
In pseudo code, the first method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = i + 1; j != i; j++) {
if (j is_larger_than array_end) {
set j equal to array_start
}
print array_element[j]
}
}
In pseudo code, the second method could be written as:
for (i = array_start; i < array_end; i++) {
print array_element[i]
for (j = array_start; j < array_end; j++) {
if (j is_not_equal_to i) {
print array_element[j]
}
}
}
public void printArray(String[] s){
for (int i = 0; i < s.length; i++) {
System.out.print("\"" + s[i] + "\",");
for (int j = 0; j < s.length; j++) {
if (j != i) {
System.out.print("\"" + s[j] + "\",");
}
}
System.out.println();
}
}
This sounds like a homework question so while I feel I shouldn't answer it, I'll give a simple hint. You are looking for an algorithm which will give all permutations (combinations) of the "for loop index" of the elements not the elements themselves. so if you have three elements a,b,c them the index is 0,1,2 and all we need is a way to generate permutations of 0,1,2 so this leads to a common math problem with a very simple math formula.
See here: https://cbpowell.wordpress.com/2009/11/14/permutations-vs-combinations-how-to-calculate-arrangements/
for(int i=0;i<s.length;i++){
for(int j=i;j<s.length+i;j++) {
System.out.print(s[j%(s.length)]);
}
System.out.println();
}
Using mod is approppiate for this question. The indexes of the printed values for your first example are like this;
0 1 2
1 2 0
2 0 1
so if you write them like the following and take mod of length of the array (3 in this case) you will reach solution.
0 1 2
1 2 3
2 3 4
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm new to programming. I'm sure the answer for this question is out there, but I have no idea what to search for.
Ok, I'll go right to it.
Here's my code:
int[] arr;
arr = new int[5];
arr[0] = 20;
arr[1] = 50;
arr[2] = 40;
arr[3] = 60;
arr[4] = 100;
System.out.println(arr);
This compiles and works fine. It's just the output from CMD that I'm dizzy about.
This is the output: [I#3e25a5.
I want the output to represent the exact same numbers from the list (arr) instead. How do I make that happen?
Every object has a toString() method, and the default method is to display the object's class name representation, then # followed by its hashcode. So what you're seeing is the default toString() representation of an int array. To print the data in the array, you can use:
System.out.println(java.util.Arrays.toString(arr));
Or, you can loop through the array with a for loop as others have posted in this thread.
System.out.println(Arrays.toString(arr));
The current output is classtype#hashcode.
Incase you need to print arrays with more than one dimension use:
Arrays.deepToString(arr);
Also remember to override toString() method for user-defined classes so that you get a representation of the objet as you choose and not the default represention which is classtype#hashcode
It's the default string representation of array (the weird text).
You'll just have to loop through it:
for(int i : arr){
System.out.println(i);
}
To print the values use.
for(int i=0; i<arr.length; i++)
System.out.println(arr[i]);
Like this:
for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}
That "weird number" is the reference for the array you printed out. It's the default behavior built into the java.lang.Object toString() method.
You should override it in your own objects if seeing the reference isn't sufficient.
It prints it's .toString() method you should print each element
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
}
or
for(Integer i : arr) {
System.out.println(i);
}
BTW You can write
int[] arr = { 20, 40, 60, 40, 60, 100 };
System.out.println(Arrays.toString(array));
or even
System.out.println(Arrays.toString(new int[] { 20, 40, 60, 40, 60, 100 }));
or
System.out.println(Arrays.asList(20, 40, 60, 40, 60, 100));
for (int i = 0; i < arr.length; ++i)
{
System.out.println(arr[i]);
}
Use Arrays.toString() and PrintStream.printf(String format, Object... args).
System.out.printf("%s%n", Arrays.toString(arr));
You printed the reference and not the values at the reference... One day it will all become clear with C.
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);
class ArrayApp{
public static void main(final String[] args){
long [] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
for(i=0;i<arr;i++) {
System.out.println(arr[i]);
}
}
}
I get this error,
ArrayApp.java:10: operator < cannot be applied to int,long[]
for(i=0;i<arr;i++) {
^
You need to use the size of the array, which would be arr.length.
for (int i = 0; i < arr.length; ++i)
As of Java 1.5, you can also use the for each loop if you just need access to the array data.
for ( long l : arr )
{
System.out.println(l);
}
arr is an object of long[] , you can't compare int with it.
Try arr.length
Alternatively You should go for
for(long item:arr){
System.out.println(item);
}
You want arr.length
The question has to be seen in the context of a previous question!
From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.
In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):
long[] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2; // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {
System.out.println(arr[i]);
}
Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:
List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
System.out.println(value);
Long arr = new Long[100];
arr[0]=112;
arr[1]=111;
for(int i=0;i<arr.length;i++) {
if (arr[i] != null ) {
System.out.println(arr[i]);
}
}
if you want to show only those which are filled.
You can solve your problem using one line of code:
Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");
See http://java.dzone.com/articles/useful-abuse for more similar tricks.