I am taking the size of an array in a variable in a loop. Each time I have to assign the size of the array equal to that variable and then take integers equal to that size. For example:
for(i = 0; i < N; i++)
{
variable = sc.nextInt();
int []array = new int[variable];
for(j = 0; j < variable; j++)
{
array[j] = sc.nextInt();
}
}
Please provide me the most efficient method as I am new to java :)
Maybe you need something like this :
List<int[]> list = new ArrayList<>();//create a list or arrays
for (int i = 0; i < n; i++) {
int variable = sc.nextInt();
int[] array = new int[variable];
for (int j = 0; j < variable; j++) {
array[j] = sc.nextInt();
}
list.add(array);//add your array to your list
}
You can create a list of arrays and initialize them on outer loop and add values to arrays using position i and j.
// initialize list with n, though you can also use 2D array as well
List<int[]> array = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
variable = sc.nextInt();
// create an array and add it to list
array.add(new int[variable]);
for (int j = 0; j < variable; j++) {
// fetch the array and add values using index j
array.get(i)[j] = sc.nextInt();
}
}
for(i=0;i<N;i++)
{
variable = sc.nextInt();
ArrayList array = new ArrayList(variable)
for(j=0;j<variable;j++)
{
int input = sc.nextInt()
array.add(input);
}
}
If an ArrayList works, this is how I'd do it.
My fourth for loop, for (int y), keeps printing the first m elements over and over again, how can i fix it so that it prints m elements at a time but not the same ones?
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
ArrayList<String> myname = new ArrayList<String>(n);
ArrayList<Integer> myscore = new ArrayList<Integer>(m);
for (int i = 0; i < n; i++) { //swimmers
myname.add(input.next());
for (int j = 0; j < m; j++) { //judges
myscore.add(input.nextInt());
}
}
for (int x = 0; x < n; x++) { //name
System.out.println(myname.get(x));
for (int y = 0; y < m; y++) { //score
System.out.println(myscore.get(y));
}
}
Based on your code it seems that you have ‘n’ number of swimmers, each with ‘m’ number of scores. You are storing the names of the ‘n’ swimmers in an ArrayList, which is bad because you know the number will never change. A better approach to this would be to declare myname as a String[] of size n, and instead of calling myname.get(x) you would later call myname[x].
This however, is only symptomatically related to the problem at hand. You are storing all of your score results inside a single ArrayList. A better solution is to generate ‘n’ number of arrays (which is what I assume you would like to do based on the title of this question). This can be done by simply declaring
allScores[][] = new int[n][m]
This would let you access the values for swimmer number ‘n’ with allScores[n]. If this isn’t what you actually wanted to do then you can simply offset the values in your last get statement by the number of scores you’ve already processed (x*n).
TLDR: Change the line in your last for loop to read:
System.out.println(myscore.get(y + x*n)
Because you have a list myscore of n*m length not only m like you thought. You are adding at the end of the list every score.
So you have n blocks of m elements in the list. You could still print the value with
for(int y = x * m, to = x*m + m; y < to; ++y){
System.out.println(myscore.get(y));
}
class ScoreHolder{
String name = "";
ArrayList<Integer> scores = new ArrayList<Integer>;
public ScoreHolder(String name){
this.name = name
}
}
And then
ScoreHolder[] scores = new ScoreHolder[n];
for (int i = 0; i < n; i++) { //swimmers
scores[i] = new ScoreHolder(input.next());
for (int j = 0; j < m; j++) { //judges
scores[i].scores.add(input.nextInt());
}
}
for (int x = 0; x < n; x++) { //name
System.out.println(scores[x].name);
for (int y = 0; y < m; y++) { //score
System.out.println(scores[x].scores.get(y));
}
}
It won't be just easy to work with now but also a lot easier to make any changes or do anything else you want.
What I have done is simply created a holder class which will hold the swimmer's name and a list of all his scores.
This abstraction will now help you in getting the scores of the swimmers or doing anything else you now want with it.
This following of my program should recieve an array of objects and sort them based on the size of their privilege variable. The "arrayFromBefore" variable is filled with objects of type MyClass. It just basically creates a new MyClass object and returns it with the same attributes of the object.
The problem is, in certain cases, there seems to be several occurences of the same MyClass object in the priority array. These duplications are also not always the same multiple (e.g. one object occurs 3 times in a row, another 5 times in a row, another twice, etc...)
MyClass[] priorityArray = new MyClass[arrayFromBefore.length];
for (int i = 0; i < priorityArray.length; i++) {
int maxIndex = 0;
int maxPrivilege = arrayFromBefore[i].returnPrivilege();
for (int j = 1; j < arrayFromBefore.length; j++) {
int currentPrivilege = arrayFromBefore[j].returnPrivilege();
if (currentPrivilege > maxPrivilege) {
maxPrivilege = currentPrivilege;
maxIndex = j;
}
}
MyClass mostPrivilaged = arrayFromBefore[maxIndex];
priorityArray[i] = mostPrivileged;
arrayFromBefore[maxIndex].setPriority(-900000000);
}
The problem is in your inner for-loop where for each i, j starts from same value 1. j should start exactly from next to i, so that same object cannot be overrided.
MyClass[] priorityArray = new MyClass[arrayFromBefore.length];
for (int i=0; i<priorityArray.length - 1; i++) {
int maxIndex = 0;
int maxPrivilege = arrayFromBefore[i].returnPrivilege();
for (int j=1+i; j<arrayFromBefore.legnth; j++) {
int currentPrivilege = arrayFromBefore[j].returnPrivilege();
if (currentPrivilege > maxPrivilege) {
maxPrivilege = currentPrivilege;
maxIndex = j;
}
}
// priorityArray[i] = mostPrivileged; this line can be removed as it isn't required because you are getting sorted arrayFromBefore.
myClass mostPrivilaged = arrayFromBefore[maxIndex]; // Swapping of
arrayFromBefore[maxIndex] = arrayFromBefore[i]; // largest priority object
arrayFromBefore[i] = mostPrivilaged; // with its required position in sorted array.
}
After this you will get arrayFromBefore as shorted in descending order of priority.
I have a board game define as
boardArray = new int[4][4];
and I have a string in this format:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"
Is there a way to put it in the int array? Consider that it should look like this
[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
You could simply do the following:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";
String myNums[] = s.split("[^0-9]+");
//Split at every non-digit
int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
//The 1 accounts for the extra "" at the beginning.
}
}
//Prints the result
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++)
System.out.print(my_array[i][j]);
System.out.println();
}
If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ
The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests
MDDA<Integer> array = new MDDA<Integer>(4,4);
or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:
Integer[] template = new Integer[] {0,0,2,0, 0,0,2,0, 0,0,0,0, 0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);
//instead of array[1][2];
array.get(1,2); // 2
I'm having some problems with Object arrays. I've made up my own object which only has an empty constructor, a constructor which initializes its two instance variables with paramaters and get/set methods.
I initiliaze the array like this:
private Bara[][] card = new Bara[3][4];
and I'm trying to fill in the object's variables like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
card[i][j].setName(name);
card[i][j].setSide(side);
}
}
Any help is appreciated.
Thanks!
private Bara[][] card = new Bara[3][4];
It just creates a two-d array for the referrences of Bara, but no Bara objects.
Thus, you need to create actual Bara Objects in your loop:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
card[i][j] = new Bara(name, side); //If such constructor exists.
}
}