Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to create an array of arrays so that i can have an array of years that breaks down into an array of 12 months that then can be broken down into 31 days. I am not sure if this process is doable in java or not, just trying to find a good method. thanks
You have to be way more specific about what you want to do, or what you have done, or any of that. But because you asked about collections of collections
You can use a multi-dimensional array. http://www.java2s.com/Tutorial/Java/0140__Collections/ArrayOfstringArrays.htm
String[][] cartoons = {
{ "Flintstones", "Fred", "Wilma", "Pebbles", "Dino" },
{ "Rubbles", "Barney", "Betty", "Bam Bam" },
{ "Jetsons", "George", "Jane", "Elroy", "Judy", "Rosie", "Astro" },
{ "Scooby Doo Gang", "Scooby Doo", "Shaggy", "Velma", "Fred", "Daphne" } };
Or Check out the API for ArrayList: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
This is how you would use one though.
ArrayList<String[]> year= new ArrayList<>();
String[] february = new String[28];
year.add(february);
Though you need to be more specific about what you want to do. Because using collections to handle temporal data is a fools errand.
You could simply create a two(or more) dimensional array
int[][] array = new int [5][12];
This would be an array of 5 years, each with 12 months. You could go even further to make a three dimensional array (picture a cube) or even a four dimensional array (I'll let you think about that one :))
See this post: Syntax for creating a two-dimensional array
You can represent a date as an array of arrays like so:
int date [][][] = new int [2015][12][31];
for(int y = 0; y < date.length;y++){
for(int m = 0; m < date[0].length;m++){
for(int d = 0; d < date[0][0].length;d++){
date[y][m][d] = d+1;
}
}
}
But why? To access a specific date, you need the indices, but if you know the indices, you already know the date.
And some of the values of this 'calendar' are invalid, e.g. 11-31,02-30,...
Related
This question already has answers here:
The best way to print a Java 2D array? [closed]
(14 answers)
Closed 2 years ago.
I am new to Java and was wondering what I did wrong. I am building a simple board game, but for some reason the array prints as an array of "Ljava.lang.String;#4bec1f0c". I've read some similar questions to this problem but for some reason, the solutions that I have found does not work in my code.
Help is appreciated.
for(int row = 0; row < gameBoard.length; row++)
{
for(int col = 0; col < gameBoard[row].length; col++)
{
gameBoard[row][col] = "- ";
}
}
System.out.print(Arrays.toString(gameBoard));
if you want to every object be visible in a 2-dimension array, use this method:
System.out.print(Arrays.deepToString(gameBoard));
Arrays.toString is working in single dimension arrays.
more data and examples:
https://www.geeksforgeeks.org/arrays-deeptostring-in-java-with-example/
Arrays.toString does the right thing for one-dimensional arrays, but won't help much on two-dimensional arrays.
Use Arrays.deepToString instead.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
The snippet in the java code is here:
public class MatrixUsingVectors {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Vector<Vector<Integer> > vec= new Vector<Vector<Integer> >();
for(int i=0;i<3;i++)
{
Vector<Integer> op= new Vector<Integer>(3);
for(int j=0;j<3;j++)
{
op.add(sc.nextInt());
}
vec.add(op);
}
System.out.println(vec);
int [][] ar= new int[vec.size()][3];
vec.copyInto(ar);// this line throws ArrayStoreException
for(int[] c: ar)
{
System.out.println(c);
}
}
}
I want to store the elements of vector vec in a 2d array named ar.
I need help to deal with ArrayStoreException and want to store the elements of vec into ar.
Please help.
Vector is 1 dimensional. Array is 1 dimensional. The Vector.copyInto() method takes a i dimensional array as a parameter.
If you want to copy a Vector of Vectors into a 2 Array, then you need to loop through the 2 dimensions to do the copy
So the code would be something like:
Object[][] rows = new Object[vec.size()][];
for (int i = 0; i < vec.size(); i++)
{
Vector<Object> vectorRow = ((Vector)vec.get(i));
Object[] arrayRow = new Object[vectorRow.size()];
vectorRow.copyInto( arrayRow );
rows[i] = arrayRow;
}
I need help to deal with ArrayStoreException
That is a run time Exception. First you need to worry about the proper algorithm to copy the data. Then if you want to catch the exception you add a try/catch block to the entire algorithm.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I would like to have a display like this:
goal: each time a char is added, the matrix will automatically create an empty line after inserting a char type.
I don't know
if using a matrix is a good idea to achieve what I want
where to start, as I have not written any code yet
Thank you for helping me out, I am a beginner in java!
There exist List classes in java, which have an expandable length.
List<Character> list = new ArrayList<>();
will create (like char[] list = new char[...]; a list of chars, but of expandable length.
Usage
To insert a char item at index index (like list[index] = item;)
list.add(index, item);
To place a char item at the end of the list
list.add(item);
To access an item of list at an index index
list.get(index);
And
If you need something similar to 2D arrays (char[][] list = new char[...][...]), use
List<List<Character>> list = new ArrayList<>();
and if you add a row to the list
list.add(new ArrayList<>());
Usage
To insert a char item at row row and column col
list.get(row).add(col, item);
To place a char item at the end of row of the list
list.get(row).add(item);
To access an item of list at row row and column col
list.get(row).get(col);
You can create static arrays in Java, dynamic arrays are not possible in java, but you can use other data structures (Collections) in Java to achieve this
Here I use the concept of a jagged array to solve your problem. We can create a 2-D array, but with variable number of columns in each row. This will work only if you have a known number of rows.
char a[][] = new char[][5];
a[0] = new char[1];
a[1] = new char[6];
a[2] = new char[6];
a[3] = new char[6];
a[4] = new char[6];
You can use this concept with ArrayList.
ArrayList[][] arraylist = new ArrayList[10][];
If you are working with pattern then you should use for-loops to print / acheive the pattern.
ArrayList<ArrayList<Character> > x
= new ArrayList<ArrayList<Character> >();
x.add(new ArrayList<Character>(Arrays.asList('4')));
x.add(new ArrayList<Character>(Arrays.asList('3','x',' ',' ',' ','e')));
x.add(new ArrayList<Character>(Arrays.asList('2','x',' ','d','d','e')));
x.add(new ArrayList<Character>(Arrays.asList('1','x','a','d','d','e')));
x.add(new ArrayList<Character>(Arrays.asList(' ','1','2','3','4','5')));
System.out.println(x);
Hope it helps.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a "for" loop that is creating a variable each time through the loop. I am attempting to insert the results into an empty array at the index of the "i" in the loop. From the best I can tell it seems I need to create a ArrayList vs. an Array to make this happen.
int varNum = 10;
Array someArr = new Array ();
for (int i = 0; i < 10; i++){
varNum = varNum +i;
someArr[i] = varNum;
}
On the first loop I want the 10 to be inserted in my array at the "0 index", 11 inserted at "1 index", 12 at the "2 Index".
**The important part is that the Array is not a set size, because I do not know how many indexes I will need in the array, so I want to add them as I needed.
If you use an ArrayList you can call add like this:
int varNum = 10;
ArrayList<Integer> someArr = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
{
varNum = varNum + i;
someArr.add(varNum);
}
This will allow you to dynamically fill the ArrayList dependent upon how many values it needs to hold.
Better use an ArrayList then, and use their .add() method
someArr.add(varNum)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am practicing Java and working on arrays. As arrays size can not be changed in run time, is it possible to make 2 arrays and in run time keep storing input in the first of and then when it is full, then move to the second array by if statement. I'm basic in Java so hope my code is in the right direction. Anyway it does not work but I just want to share my idea and see if it can work.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int[] arr1 = new int[5];
int[] arr2 = new int[10];
while(in.hasNextInt())
{
for(int i = 0; i <= arr2.length; i++)
{
if (i <= arr1.length) { arr1[i] = in.nextInt(); }
else arr2[i] = in.nextInt();
}
}
}
You should change your code to the following:
if (i < arr1.length) { arr1[i] = in.nextInt(); } //"<" instead of "<="
else { arr2[i - arr1.length] = in.nextInt(); } //decrement i by the size of the first Array
As denoted in the other answer/answers, there are plenty of more practical ways to do what you are trying to achieve, but non the less the above should let your code work as inteded.
This is not a good idea. If the second array overfills, you'll have problems such as exceptions and lost data.
I recommend using the ArrayList.
You can create one:
ArrayList<Integer> list=new ArrayList<>();
and add to it with:
list.add(new Integer(in.nextInt()));
With autoboxing you can skip the creation of an integer reference object and use:
list.add(in.nextInt());
Anyway it does not work ...
Yea. Pretty obviously.
... but I just want to share my idea and see if it can work.
No. Pretty obviously.
Sure you can put elements in the second array when the first array. But then you run into the same problem all over again when when the second array fills up.
The best solution is to use an ArrayList<Integer> (... or any kind of List<Integer>). That will take care of the problem of "growing" the list transparently and automatically.
If you insist on doing this with arrays, then the solution is to:
dynamically allocate a "new" array that is bigger than the "current" array,
copy the elements of the "current" array to the "new" array, and
assign the reference for the "new" array to the "current" array variable.
In fact, you could do all of this using Arrays.copyOf(int[], int).