For loop counter in dot operator - java

I'm working in the Android ADT plugin for Eclipse.
What I try to do is this:
I have some drawables named from 0 to 150 and i want to get them into an array to use them.
As far as I know, to be usable, they have to be assigned with
"R.drawable.FilenameWithoutExtension".
To make the array creation easy and fast I want to use a for loop:
for (int i = 0; i <= 150; i++) {
imagesArray[i] = R.drawable.i;
}
But for now I get an error for that "R.drawable.i" because there is no file "i".
Is there a way to use the numeric value of "i" instead of the letter for the assignement "R.drawble."?

You can get a resource identifer from its name using the getIdentifier() method:
for (int i = 0; i <= 150; i++)
imagesArray[i] = getResources().getIdentifier(String.valueOf(i), "drawable", "your.package.name");

The file names must start with a letter because at build time the file names are converted to java identifiers.
After you do that you can use reflection access each of the members of R.drawable.

Related

How to get values of vars by its name

I'm using the CPLEX Java interface to do some MIP problems, the optimizer is doing well but I can't get values of vars by their names.
The definitions of my vars are in a for loop, so in the outer code, I can't use cplex.getValue() function to get their values.
Please remind me of any methods that can get all the values or get values by their names.
for (int i = 0; i < count; ++i){
// c1 is changing when i increase
IloNumVar[] x = new IloNumVar[c1];
for (int j = 0; j < c1; ++j) {
x[j] = cplex.numVar(0, 1, IloNumVarType.Int, "x" + String.valueOf(i) + "_" + String.valueOf(j));
}
}
...
cplex.solve();
How to retrieve all x values outer for loop after cplex.solve()?
Just don't try to recover them by their names. Keep your CPLEX variables in lists, arrays, dictionaries, structures, class instances or whatever in your code. Your IloNumVars are just normal objects that can be stored like any other. In your example code, just keep those IloNumVar arrays in a structure declared outside the loop (e.g. a list of those IloNumVar[] arrays).
If you really need to retrieve them by name, then put them in a dictionary, keyed on the variable name - again that would have to be declared outside your loop above. But that would be less efficient than just keeping them in your usual Java data structures as it would require extra lookup processing inside the ictionary to find the item by name.

Defining a binary decision variable in java using cplex

I am trying to define a binary decision variable in java using cplex. That's a two dimensional variable. It means that if a path starts from a specific station it should be 1 or otherwise 0. I have a set of station, J and a set of paths, K and my decision variable is Z_jk. Currently I am defining the code like following, but it doesn't work. Could anybody please help me?
Thanks in advance.
// define variables
z = new IloNumVar[stations_start.size()][];
for (int j=0; j<stations_start.size();j++) {
z[j] = cplex.numVarArray(paths.size(),0,1);
for (int k=0;k<paths.size();k++) {
z[j][k] = cplex.numVar(new_column, 0, 1,"z");
z[j][k].setName("z."+j+"."+k);
}
}
You are trying to create a 2D array of binary decision variables. What errors are you getting?
Try looking at some of the sample code provided with CPLEX. See for example transport.java which includes some 2D arrays of variables declared and initialised like this:
IloNumVar[][] x = new IloNumVar[nbSupply][];
IloNumVar[][] y = new IloNumVar[nbSupply][];
for (int i = 0; i < nbSupply; i++) {
x[i] = cplex.numVarArray(nbDemand, 0., Double.MAX_VALUE);
y[i] = cplex.numVarArray(nbDemand, 0., Double.MAX_VALUE);
}
For a binary decision variable you may prefer to use IloBoolVar rather than the IloNumVar or even IloIntVar options.
You do need to declare the dimension in one of two ways, however. You've declared new IloNumVar[stations_start.size()][]; but not specified the second dimension. The easiest approach would be to declare:
z = new IloBoolVar[stations_start.size()][paths.size()];
Alternately you can keep your existing declaration, but in the loop add on the second dimension:
z = new IloBoolVar[stations_start.size()][];
for (int j=0; j<stations_start.size(); j++) {
z[j] = new IloBoolVar[paths.size()];
... existing assignments ...
}

Java for loop and class definition

Hey im very new at java so please bear with me :)
I have objects v1, v2, v3 with each one containing details of soccer players stats
int LessThan25 = 0;
for (int i = 0; i < topscorer.size(); i++)
{
while (v**[i]**.getGoals() < 25)
{
LessThan25++;
}
}
My question is that how do I make this loop work? I want to be able to use the integers in the for loop for my while v loop which links to my class definition. (bolded part)
Appreciate the help :)
I get what you mean now, you can do this to access each topScorer object:
for(int x=0; x<topScorer.size(); x++) //iterate through all elements in topScorer
if(topScorer.get(x).getGoals() < 25)
lessThan25++;
The syntax to access the elements within an ArrayList is:
list.get(x) where x is the element you wanted to access (starts from 0)
Alternatively:
Certainly, enhanced for-loop (for each loop works too):
for(Scorer s : topScorer) //Scorer is the object type in your list
if(s.getGoals() < 25)
lessThan25++;
Use 'if' condition instead of 'while', i think that is what you looking.
Use the enhanced for loop - a better idiom if using Java 5+.
Variable names should start lower case by convention.
for(Player player : players) {
if(player.getGoals < 25)
lowerThan25Goals++;
}
The answer of user3437460 is what you're looking for
for(Scorer s : topScorer)
if(s.getGoals() < 25)
lessThan25++;
An example of a Player would have been nice,
sth. like
Player cRonaldo = new Player(age, size, avgGoals, (total)goals);
Player lMessi = new Player(age, size, avgGoals, (total)goals);
Please, take a look at your while-loop
while (topScorer[i].getGoals() < 25)
{
LessThan25++;
}
This is an infinit loop. Becaue if u ever reach the point where a topScorer aka v [i] has less than '25' goals, u never get that loop to stop, and your counter LessThan25 breaking the limit of your ALU ;)
( lower case variables! )
Could be a mistake, or missing code you provided.
So just for you, being 'new' to Java, to know.
If you're using Java 8, you can easily solve this problem using Stream API in only one line of code:
long lessThan25 = topScorer.stream()
.filter(element -> element.getGoals() < 25).count();
Moreover, using Streams the JVM can improve performance in background.

Changing Filenames(Strings) through loops - Java

I want to change images at a specific location, for the purpose of animation. Can I create a loop with for change in file names. File names are like Sprite1.png, Sprite2.png ...... Sprite10.png.
for(i = 1; i <= 10; i++)
{
Display("Sprite(i).png")
}
Is something like this possible? How?
Lets say there are n files. you can achieve desired output by using the following piece of code
for(i=1;i<=n;i++){
Display("Sprite"+i+".png")
}

Incompatible data types in Java, array and integer

I'm trying to get a program so that it loops and adds up the sum of an array. My code appears to be working, with the exception that it states that the text[j] in adding = adding + text[j] is an incompatible type (I'm assuming data type). Earlier in the code, I have int adding = 0;. This is the erroneous code:
for (int j=0;j<=total;j++){
adding = adding + text[j];
System.out.println(text[j]);
}
where total is the limiting factor. If I put:
for (int j=0;j<= total;j++){
adding = adding + j;
System.out.println(text[j]);
}
the program compiles but gives 45, which is incorrect.
Why is this happening? Thanks!
The answer actually turned out to be outside the code given. I had set my array to be a String, not an int as it should have been.
If your text[] is String[] or char[] as the name suggests then I believe you are trying to update text[] elements with suffix j or adding, which you can write as:
If it is char[] then write
text[j] = (char)(adding + (int)text[j]);
If it is String[] then write
text[j]= text[j]+adding;
as required. It all depends on what is the data type of text[] and what are you trying to achieve?
Also as suggested in one of the answers, if total is length of the array, then change the comparison to < to avoind ArrayIndexOutOfBoundsException
Your second example, adds j into adding but prints text[j] value, which is nothing to do with the addition of adding and j.

Categories