I have the following function:
strNameValue = prefs.getString("NamePosition", "");
inNameValueConversion = Integer.parseInt(strNameValue);
if (inNameValueConversion == 0) {
DisplayInformation(inNameValueConversion, R.raw.audio01);
}
if (inNameValueConversion == 1) {
DisplayInformation(inNameValueConversion, R.raw.audio02);
}
if (inNameValueConversion == 2) {
DisplayInformation(inNameValueConversion, R.raw.audio03);
}
if (inNameValueConversion == 3) {
DisplayInformation(inNameValueConversion, R.raw.audio04);
}
Because all the audio file starts with audio and only the number changes at the end I wanted to create a function which allows me to use less code like this:
public void DisplayInformation(int inNum, final int inSoundResource) {
if (inSoundResource < 2) {
strIConv = String.valueOf("0" + inSoundResource);
inConv = Integer.parseInt(strIConv);
int k = R.raw.audio+"inConv";
}
}
I get the following error: audio cannot be resolved or is not a field
How do I edit the above code so I can just use one function instead of using so many IF statement, since it will be 90+ times.
You can use getIdentifier(), so your code would look like this:
public void displayInformation(int inNum) {
String id = "audio";
// for inNum < 9, we need to add 0, so for example when you pass 0
// id will be 01, not 1
if (inNum < 9) then id += "0";
//based on your code, 0 - audio01, 1 - audio02 etc, so add 1
id += (inNum + 1);
// call getIdentifier with string containing resource name, which are in your raw folder
// and in your package
int k = getResources().getIdentifier(id, "raw", "your.package.name.here");
//k now contains an id of your resource, so do whatever you want with it
}
and your code can then be reduced to this:
strNameValue = prefs.getString("NamePosition", "");
inNameValueConversion = Integer.parseInt(strNameValue);
displayInformation(inNameValueConversion);
Remember to use your package name in the call to getIdentifier().
Docs are here: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)
You could try to do it like it is mentioned in this post: https://stackoverflow.com/a/5626631/3178834
In your case, you have to create an array for all audio files as resources xml and then load it with res.getXml into java. Just follow the link from above.
Building R values that way won't work -- you'll need to use reflection instead.
For example:
import java.lang.reflect.Field;
/* ... */
int id = R.id.class.getField("video" + i).getInt(0);
Related
I need to create a method which checks each element in my array to see if it is true or false, each element holds several values such as mass, formula, area etc for one compound, and in total there are 30 compounds (so the array has 30 elements). I need an algorithm to ask if mass < 50 and area > 5 = true .
My properties class looks like:
public void addProperty (Properties pro )
{
if (listSize >=listlength)
{
listlength = 2 * listlength;
TheProperties [] newList = new TheProperties [listlength];
System.arraycopy (proList, 0, newList, 0, proList.length);
proList = newList;
}
//add new property object in the next position
proList[listSize] = pro;
listSize++;
}
public int getSize()
{
return listSize;
}
//returns properties at a paticular position in list numbered from 0
public TheProperties getProperties (int pos)
{
return proList[pos];
}
}
and after using my getters/setters from TheProperties I put all the information in the array using the following;
TheProperties tp = new properties();
string i = tp.getMass();
String y = tp.getArea();
//etc
theList.addProperty(tp);
I then used the following to save an output of the file;
StringBuilder builder = new StringBuilder();
for (int i=0; i<theList.getSize(); i++)
{
if(theList.getProperties(i).getFormatted() != null)
{
builder.append(theList.getProperties(i).getFormatted());
builder.append("\n");
}
}
SaveFile sf = new SaveFile(this, builder.toString());
I just cant work out how to interrogate each compound individually for whether they reach the value or not, reading a file in and having a value for each one which then gets saved has worked, and I can write an if statement for the requirements to check against, but how to actually check the elements for each compound match the requirements? I am trying to word this best I can, I am still working on my fairly poor java skills.
Not entirely sure what you are after, I found your description quite hard to understand, but if you want to see if the mass is less than 50 and the area is greater than 5, a simple if statement, like so, will do.
if (tp.getMass() < 50 && tp.getArea() > 5) {}
Although, you will again, have to instantiate tp and ensure it has been given its attributes through some sort of constructor.
Lots of ways to do this, which makes it hard to answer.
You could check at creation time, and just not even add the invalid ones to the list. That would mean you only have to loop once.
If you just want to save the output to the file, and not do anything else, I suggest you combine the reading and writing into one function.
Open up the read and the write file
while(read from file){
check value is ok
write to file
}
close both files
The advantage of doing it this way are:
You only loop through once, not three times, so it is faster
You never have to store the whole list in memory, so you can handle really large files, with thousands of elements.
In case the requirements changes, you can write method that uses Predicate<T>, which is a FunctionalInterface designed for such cases (functionalInterfaces was introduced in Java 8):
// check each element of the list by custom condition (predicate)
public static void checkProperties(TheList list, Predicate<TheProperties> criteria) {
for (int i=0; i < list.getSize(); i++) {
TheProperties tp = list.get(i);
if (!criteria.apply(tp)) {
throw new IllegalArgumentException(
"TheProperty at index " + i + " does not meet the specified criteria");
}
}
}
If you want to check if mass < 50 and area > 5, you would write:
checkProperties(theList, new Predicate<TheProperties> () {
#Override
public boolean apply(TheProperties tp) {
return tp.getMass() < 50 && tp.getArea() > 5;
}
}
This can be shortened by using lambda expression:
checkProperties(theList, (TheProperties tp) -> {
return tp.getMass() < 50 && tp.getArea() > 5;
});
I please bear with me, I have been using Java for 2 days and i've hit a bit of a hurdle.
I am using Talend to perform a count using the tMemorize and tJava components but this may be a question for a Java developer. I have previously posted an issue with using this method within a joblet by my new issue is more Java related which can be viewed here:
using Joblets in talend with tMemorize and tJavaFlex
I need to reference an array generated by the java code talend. I cannot reference this element directly because of an issue with using tJavaFlex within multiple joblets: Java renames joblets each time they are used.
It may be useful to understand how my code works in normal circumstances (excluding the use of joblets).
int counter = 1;
if (EnquiryID_mem_1_tMemorizeRows_1[0].equals(EnquiryID_mem_1_tMemorizeRows_1[1]))
{
counter++;
}
row3.counter = counter;
The EnquiryID_mem_1_tMemorizeRows_1[0] and EnquiryID_mem_1_tMemorizeRows_1[1] is what I need to reference.
To overcome this I have written the following code.
String string = currentComponent;
String[] parts = string.split("_");
String part1 = parts[0];
String part2 = parts[1];
String joblet = part1+'_'+part2;
String newrow = "EnquiryID_"+joblet+"_tMemorizeRows_1"
if (newrow[0].equals(newrow[1]))
{
counter++;
}
row3.counter = counter;
However I get the following error:
The type of the expression must be an array type but it resolved to String
I understand that the newrow variable is a string and I am using it to reference an array. I have searched far and wide online for a resolve but I cannot fine one. Can someone help me please?
Thank you
Here is the talend code that my code should reference. I have taken it from the currentComponent that I am using to when it changes to one not in use directly.
currentComponent = "mem_1_tMemorizeRows_1";
// row1
// row1
if (execStat) {
runStat.updateStatOnConnection("row1" + iterateId,
1, 1);
}
for (int i_mem_1_tMemorizeRows_1 = iRows_mem_1_tMemorizeRows_1 - 1; i_mem_1_tMemorizeRows_1 > 0; i_mem_1_tMemorizeRows_1--) {
EnquiryID_mem_1_tMemorizeRows_1[i_mem_1_tMemorizeRows_1] = EnquiryID_mem_1_tMemorizeRows_1[i_mem_1_tMemorizeRows_1 - 1];
}
EnquiryID_mem_1_tMemorizeRows_1[0] = row1.EnquiryID;
mem_1_row2 = row1;
tos_count_mem_1_tMemorizeRows_1++;
/**
* [mem_1_tMemorizeRows_1 main ] stop
*/
/**
* [mem_1_tJavaFlex_1 main ] start
*/
currentComponent = "mem_1_tJavaFlex_1";
// mem_1_row2
// mem_1_row2
if (execStat) {
runStat.updateStatOnConnection("mem_1_row2"
+ iterateId, 1, 1);
}
mem_1_row3.QuoteID = mem_1_row2.QuoteID;
mem_1_row3.EnquiryID = mem_1_row2.EnquiryID;
if (EnquiryID_mem_1_tMemorizeRows_1[0]
.equals(EnquiryID_mem_1_tMemorizeRows_1[1])) {
rower++;
}
mem_1_row3.rower = rower;
tos_count_mem_1_tJavaFlex_1++;
/**
* [mem_1_tJavaFlex_1 main ] stop
*/
/**
* [mem_1_tMap_1 main ] start
*/
currentComponent = "mem_1_tMap_1";
Thank you to everyone who has helped so far.
This
if (newrow[0].equals(newrow[1]))
Tries to pick the first and second element of the array newrow. Unfortunately you declare newrow as
String newrow = "EnquiryID_"+joblet+"_tMemorizeRows_1"
which is not an array but a String. That syntax in the if will not work with a String. I am not sure what you are trying to do but that if check will not work.
EDIT:
If you are trying to pick up char from a string you need to use charAt(index).
If you want to treat newrow as an array you have to declare it as such and pass appropriate elements to it.
EDIT 2: I think you are trying to pass the actual data in joblet to newrow in this:
String newrow = "EnquiryID_"+joblet+"_tMemorizeRows_1"
But what happens here is that everything is concatenated in one String so you need to figure out where the data you are looking for (part[0] and part[1] I assume) is present in that String so you can pull them out (basically what indices contain the values you are looking for).
An example of how newrow will look after that assignment:
"EnquiryID_part1_part2_tMemorizeRows_1"
So "part1" will start at index 10 and will end at index 14. I am just using "part1" here, but it would have whatever value is stored in part1 variable.
If you can show us what you expect it to look like that would help.
I'm not super familiar with talend (understand: not at all). But it sounds like you have some sort of attribute of a generated class (say myGeneratedObject) and you want to access it by name.
In that case, you could do something like:
String newrow = "EnquiryID_"+joblet+"_tMemorizeRows_1"
Field field = myGeneratedObject.getClass().getField(newrow);
if (field.getClass().isArray()) {
if(Array.get(field, 0).equals(Array.get(field, 1)) {
counter++;
}
}
It all depends how you access that field really and where it's declared. But if it's an attribute of an object, then the code above should work, +/- contextual adjustments due to my lack of knowledge of the exact problem.
I am currently making a text adventure game in Java, but I have come across a problem:
I need the value of a String variable to change each time the value of a particular int variable changes.
I want the program to perform this task (then continue where it left off) each time the value of an int variable changes:
if (enemyposition == 1) {
enemyp = "in front of you";
}
else if (enemyposition == 2) {
enemyp = "behind you";
}
else if (enemyposition == 3) {
enemyp = "to your left";
}
else if (enemyposition == 4) {
enemyp = "to your right";
}
else {
enemyp = "WOAH";
}
Thanks! :D
You could make the code much shorter using an array.
String[] message = {"WOAH", // 0
"in front of you", // 1
"behind you", // 2
"to your left", // 3
"to your right"}; // 4
enemyp = (enemyposition > 0 && enemyposition < 5) ? message[enemyposition] :
message[0];
The question you're asking sounds like it might be answerable by creating a class to hold the enemyposition integer. Add a "setter" method to your class to set the integer. You can write your setter method so that when the integer is set, it also sets up a string. Then write a "getter" method to retrieve the string. That's one common way of making sure two variables change together.
public class EnemyPosition {
private int enemyposition;
private String enemyp;
public void setPosition(int n) {
enemyposition = n;
enemyp = [adapt your code to set this based on the position]
}
public String getEnemyp() {
return enemyp;
}
}
I'm sure there are a lot of details missing, but you get the idea. Then instead of int enemyposition in the rest of your code, use EnemyPosition enemyposition = new EnemyPosition(), and use the setPosition method instead of assigning to it.
That's not the only solution (an array or Map that maps integers to strings may be good enough), but it's one OOP way to do things.
I have been working on this program for hours, and have worked out nearly all of the errors that have cropped up in every other class. This one, however, I can's seem to fix the receive method. The receive method should first check (by comparing SKUs) whether or not the incoming product is already in myCatalog. If not, add the product (via its SKU) to the catalog. After that, in any case -- as long as there is still some of the incoming product not yet been placed in a bin -- I want to locate which bin contains the least total quantity. (If all the bins are full, add a new, empty bin to use)I'd add that specific product to that bin until the bin is either full -- at which point I'd repeat -- or I run out of the product. This repeats until no more incoming product is left.
public class Warehouse
{
private int myBinMax;
private ArrayList<MusicMedia> myCatalog;
private ArrayList<Bin> myBins;
public Warehouse( int binMax )
{
myBinMax = binMax;
myCatalog = new ArrayList<MusicMedia>();
myBins = new ArrayList<Bin>( 5 );
}
public String toString()
{
return Tester.detailedInventory(myCatalog,myBins);
}
public void addBin()
{
myBins.add( new Bin( "B" + myBins.size() ) );
}
public void receive( MusicMedia product, int quantity )
{
boolean contained = false;
int lowestAmount = myBinMax,
leastFullBinIndex,
i,
insertQuantity;
for(MusicMedia entry : myCatalog)
{
if(entry.getSKU().equals(product.getSKU()))
{
contained = true;
}
}
if(!contained)
{
myCatalog.add(product);
}
while(quantity > 0)
{
lowestAmount = myBinMax;
for(i = 0; i < myBins.size(); i++)
{
if(myBins.get(i).totalQuantity() < lowestAmount)
{
lowestAmount = myBins.get(i).totalQuantity();
leastFullBinIndex = i;
}
if((i == myBins.size() - 1 && lowestAmount == myBinMax)||(myBins.size() == 0))
{
myBins.add(new Bin("bin" + Integer.toString(i)));
}
}
if(quantity >= myBinMax - lowestAmount)
{
insertQuantity = myBinMax - lowestAmount;
}
else
{
insertQuantity = quantity;
}
quantity -= insertQuantity;
myBins.get(i).add(new BinItem(product.getSKU(), insertQuantity));
}
}
}
Before my last edit, nothing would print -- just a blank console -- but in an attempt to fix that, I added this (also contained within the code above):
if((i == myBins.size() - 1 && lowestAmount == myBinMax)||(myBins.size() == 0))
{
myBins.add(new Bin("bin" + Integer.toString(i)));
}
Now, it won't run without giving me an error:
java.lang.IndexOutOfBoundsException
Index: 0, Size 0 (in java.util.ArrayList)
As well as highlighting the following line:
myBins.get(i).add(new BinItem(product.getSKU(), insertQuantity));
Here's a breakdown on the various classes that have been created for this colossal program:
MusicMedia has three private variables, but the only one that has any bearing here is the String mySKU, obtained by getSKU()
Bin has a private String, name, which is also its only argument, as well as a private ArrayList of class BinItem. In order to access this ArrayList of BinItems from another class, you would use getContents(). It also has method totalQuantity(), which returns the total quantity of objects already in a bin.
BinItem has private variables mySKU (String) and myQuantity (int) and methods getSKU() and getQuantity(), both being its arguments in that order
So to start with you have no bins.
Your "for" block is skipped because size is zero;
So we get to the final line of the "while" loop, and we execute myBins.get(i)...
This is where we get the error because we can't get the bin at index 0, because we got no bins at all.
The problem is we reached this line of code without adding any bins...
I'm not sure if you realized, the line below doesn't start your program with 5 bins.
myBins = new ArrayList<Bin>( 5 );
The 5 in this code sets the internal buffer for the array to hold 5 items. If we supplied no number it would start with 10. But the numbers are just there to give programmers control over how much memmory is initalized.
If your goal was to start with 5 bins, you should do something as follows:
myBins = new ArrayList<Bin>( 5 );
for(int i=0; i<5; i++){
myBins.add(new myBin());
}
simonn helped me to code an ordered integer partition function here. He posted two functions: one function simply gives back the count of partitions, the second function gives the partitions as a list.
I've already managed to translate the first function from Java to PHP:
Java version
PHP version
Unfortunately, I can't manage to translate the second function. Can anyone help me and translate this small function for me?
public class Partitions2
{
private static void showPartitions(int sizeSet, int numPartitions)
{
showPartitions("", 0, sizeSet, numPartitions);
}
private static void showPartitions(String prefix, int start, int finish,
int numLeft)
{
if (numLeft == 0 && start == finish) {
System.out.println(prefix);
} else {
prefix += "|";
for (int i = start + 1; i <= finish; i++) {
prefix += i + ",";
showPartitions(prefix, i, finish, numLeft - 1);
}
}
}
public static void main(String[] args)
{
showPartitions(5, 3);
}
}
It would be great if the solution would be one single function instead of a class with several functions.
Thank you very much in advance! And thanks again to simonn for this great answer!
You probably don't need the main method, that just seems to be a test rig showing how to invoke the other method.
The problem mapping this code directly to PHP is that you can't overload method names in PHP. Instead you should concentrate on translating the second version of the showPartitions function. If you need a 2-argument version you can use default values for the prefix and start parameters (you'll have to change the parameter order to do this because in PHP optional parameters must come last).
Here's my (untested) attempt at translating the most important function:
function showPartitions($prefix, $start, $finish, $numLeft)
{
if ($numLeft == 0 && $start == $finish) {
echo $prefix."\n";
} else {
$prefix .= "|";
for ($i = $start + 1; $i <= $finish; $i++) {
$prefix .= $i.",";
showPartitions($prefix, $i, $finish, $numLeft - 1);
}
}
}