I'm relatively new to Java and trying to create an application to help with my trading. I have a method to read a csv file that I input, which is table with x number of rows and 3 columns. It reads it as multidimensional String array (String[][]) Eg
Pair----- Buy Price ---Sell Price
AUDUSD 0.9550 --- 0.9386
EURUSD 1.3333 --- 1.3050
GBPUSD 1.5705 --- 1.5550
(please excuse my formatting)
I have a constructor called ForexPair that looks like this:
public class ForexPair extends PriceWarning{
public String pairName;
public double buyPrice;
public double sellPrice;
public ForexPair(String pair, String buy, String sell) {
pairName = pair;
buyPrice = Double.valueOf(buy);
sellPrice = Double.valueOf(sell);
}
My question is this: Can I use a 'for' loop to create an object for each row in my CSV file? I believe I can use an ArrayList for this. However I want the name of each object I create to be the Pair Name in the first column of my csv file. For example:
ForexPair AUDUSD = new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2]));
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
Currently I have this code:
public static void main(String[] args) {
String[][] myArray = getInputArray();
String[] pairNames = new String[myArray.length];
for(int i = 0; i < pairNames.length; i++){
pairNames[i] = myArray[i][0]; //Creates 1D String array with pair names.
ForexPair pairNames[i] = new ForexPair(pairNames[i], (myArray[i][1]),(myArray[i][2]));
}
}
Variable names are not relevant - they aren't even kept track of after your code is compiled. If you want to map names to objects you can instead place ForexPair instances in a Map<String, ForexPair>, i.e.
Map<String, ForexPair> map = new HashMap<String, ForexPair>();
...
// in the for-loop:
map.put(pairNames[i], new ForexPair(pairNames[i], myArray[i][1],myArray[i][2]));
Although this seems slightly redundant, as you already have the name as a field in each ForexPair, so you might want to consider removing this field and keeping track of the name only via the map.
Yes you can. Use a HashMap.
rough example:
HashMap<String, ForexPair> myMap = new HashMap<String, ForexPair>();
myMap.put("AUDUSD", new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2])));
ForexPair pair = myMap.get("AUDUSD");
1.
Can I use a 'for' loop to create an object for each row in my CSV file?
Yes, that's possible:
BufferedReader br = new BufferedReader(new FileReader(yourCsvFile));
String line;
while((line = br.readLine()) != null) {
// do something with line.
}
2.
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
I think your mixing up two different concepts: name of variable and value of your variable called pair
The value of your variable is the important point, while the name of your variable only provides code quality!
final TableLayout tview = (TableLayout) findViewById(R.id.tblGridStructure);
final JSONArray JarraymenuItems = {item1,it3m1mwer,wer,ds};//your list of items
for (int i = 0; i < JarraymenuItems.length(); i++)
{
ableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tview.addView(tr, LayoutParams.FILL_PARENT, 45);
T
final TextView etprice = new TextView(this);
etprice.setText("your text value wat u want to display");
tr.addView(etprice );
int count = tview.getChildCount();
if (count % 2 != 0)
tr.setBackgroundColor(Color.parseColor("#E3E3E3"));
}
Related
Sorry for my bad English. I am using two separate string array for each item of arraylist. All things working fine . My Question is I want to take each item of String array (say) if i take string array "asasaqty" and another item of string array "asasaId" then I want to store each item of string array value in third string array (say:[id1,qty1] and so on). Please let me know if there is a proper solution for this.
Below is my code.
Thanks in advance
String [] asasaqty;
String [] asasaId;
final AddToCartData addToCartData = response.body();
shoppingBagArrayList = addToCartData.getData();
asasaqty = new String[shoppingBagArrayList.size()];
asasaId = new String[shoppingBagArrayList.size()];
for (int i = 0; i < shoppingBagArrayList.size(); i++) {
asasaqty[i] = shoppingBagArrayList.get(i).getQty();
asasaId[i]=shoppingBagArrayList.get(i).getProductId();
System.out.println("==========wwwww========"+ Arrays.toString(asasaqty));
System.out.println("======wwwwssssswwwwss======"+ Arrays.toString(asasaId));
/* HashMap<String,String> map=new HashMap<String,String>();
for (int i = 0; i < asasaqty.length; i++) {
map.put(asasaqty[i],asasaId[i]);
System.out.println("======aaaaaaa======"+ map.put(asasaqty[i],asasaId[i]));
}*/
After printing the value in logcat the value is looking like
/System.out: ==========wwwww========[3, 2]
/System.out: ======wwwwssssswwwwss======[151, 10]
Now i want to take another String array and store each item asasaqty and asasaId in separate array like below
String[] xyz = [3,151] and
String[] abc = [2,10]
Please let me know how can we do this.
You can use productID and key (Assuming it is unique) and qty as value.
HashMap<Integer,Integer> dataMap = new HashMap<>();
for (int i=0; i <shoppingBagArrayList.size; i++){
dataMap.put(shoppingBagArrayList.get(i).getProductId() , shoppingBagArrayList.get(i).getQty());
}
System.out.println("DataMap: "+dataMap);
Attempting to tidy up code, originally I was using this method of writing to arrays, which is ridiculously long when I have to repeat it 20 times
if (ant.getAntNumber() == 3)
{
numbers3.add(ant.getCol());
numbers3y.add(ant.getRow());
}
if (ant.getAntNumber() == 4)
{
numbers4.add(ant.getCol());
numbers4y.add(ant.getRow());
}
I attempted to use a for loop to do it but I cant figure out how to add to the array using the string value, because it thinks its a string rather than trying to use the array
for (int j = 0; j<maxAnts; j++)
{
String str = "numbers" + j;
String str2 = "numbers" + j + "y";
//this part doesnt work
str.add(ant.getCol());
}
Any suggestions would be helpful
In Java, you cannot use the value of a String object to reference an actual variable name. Java will think you're attempting to to call add on the String object, which doesn't exist and gives you the compiler error you're seeing.
To avoid the repetition, you need to add your Lists to two master lists that you can index.
In your question, you mention arrays, but you call add, so I'm assuming that you're really referring to Lists of some sort.
List<List<Integer>> numbers = new ArrayList<List<Integer>>(20);
List<List<Integer>> numbersy = new ArrayList<List<Integer>>(20);
// Add 20 ArrayList<Integer>s to each of the above lists in a loop here.
Then you can bounds-check ant.getAntNumber() and use it as an index into your master lists.
int antNumber = ant.getAntNumber();
// Make sure it's within range here.
numbers.get(antNumber).add(ant.getCol());
numbersy.get(antNumber).add(ant.getRow());
How about this?
Ant[] aAnt = new Ant[20];
//Fill the ant-array
int[] aColumns = new int[aAnt.length];
int[] aRows = new int[aAnt.length];
for(int i = 0; i < aAnt.length; i++) {
aColumns[i] = aAnt[i].getCol();
aRows[i] = aAnt[i].getRow();
}
or with lists:
List<Integer> columnList = new List<Integer>(aAnt.length);
List<Integer> rowList = new List<Integer>(aAnt.length);
for(Ant ant : aAnt) {
columnList.add(ant.getCol());
rowList.add(ant.getRow());
}
or with a col/row object:
class Coordinate {
public final int yCol;
public final int xRow;
public Coordinate(int y_col, int x_row) {
yCol = y_col;
xRow = x_row;
}
}
//use it with
List<Coordinate> coordinateList = new List<Coordinate>(aAnt.length);
for(Ant ant : aAnt) {
coordinateList.add(ant.getCol(), ant.getRow());
}
A straight-forward port of your code would be to use two Map<Integer, Integer> which store X and Y coordinates. From your code it seems like ant numbers are unique, i.e., we only have to store a single X and Y value per ant number. If you need to store multiple values per ant number, use a List<Integer> as value type of the Map instead.
Map<Integer, Integer> numbersX = new HashMap<Integer, Integer>();
Map<Integer, Integer> numbersY = new HashMap<Integer, Integer>();
for(Ant ant : ants) {
int number = ant.getAntNumber();
numbersX.put(number, ant.getCol());
numbersY.put(number, ant.getRow());
}
I need to create an Arraylist in a while loop with a name based on variables also in the loop. Here's what I have:
while(myScanner.hasNextInt()){
int truster = myScanner.nextInt();
int trustee = myScanner.nextInt();
int i = 1;
String j = Integer.toString(i);
String listname = truster + j;
if(listname.isEmpty()) {
ArrayList listname = new ArrayList();
} else {}
listname.add(truster);
i++;
}
The variable truster will show up more than once while being scanned, so the if statement is attempting to check if the arraylist already exists. I think I might have done that out of order, though.
Thanks for your help!
Store the ArrayLists in a Map:
Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){
// Stuff
List<String> list = new ArrayList<String>();
list.add(truster);
listMap.put(listname, list);
}
Note the use of generics (the bits in <>) to define the type of Object the List and Map can contain.
You can access the values stored in the Map using listMap.get(listname);
If I understand you correctly, create a list of lists or, better yet, create a map in which the key is the dynamic name you want and the value is the newly created list. Wrap this in another method and call it like createNewList("name").
Really not sure what you mean at all but you have some serious fundamental flaws with your code so I'll address those.
//We can define variables outside a while loop
//and use those inside the loop so lets do that
Map trusterMap = new HashMap<String,ArrayList<String>>();
//i is not a "good" variable name,
//since it doesn't explain it's purpose
Int count = 0;
while(myScanner.hasNextInt()) {
//Get the truster and trustee
Int truster = myScanner.nextInt();
Int trustee = myScanner.nextInt();
//Originally you had:
// String listname = truster + i;
//I assume you meant something else here
//since the listname variable is already used
//Add the truster concated with the count to the array
//Note: when using + if the left element is a string
//then the right element will get autoboxed to a string
//Having read your comments using a HashMap is the best way to do this.
ArrayList<String> listname = new ArrayList<String>();
listname.add(truster);
trusterMap.put(truster + count, listname);
i++;
}
Further, you are storing in myScanner a stream of Ints that will get fed in to the array, but which each have very different meanings (truster and trustee). Are you trying to read these in from a file, or user input? There are better ways of handling this and if you comment below with what you mean I'll update with a suggested solution.
I am trying to create an application which retrieves the users favourite book quote however I am stuck on how to display this information back to the user. I created an ArrayList which will store all the information. However when displaying this information, I keep getting the error:
java.lang.NullPointerException
when it tries to execute the code
temp[i] = new HashMap<String,String>();
This class is shown below:
public class FavouriteQuotesActivity extends ListActivity {
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
private void getFavorites() {
DataBaseHelper myDbHelper = new DataBaseHelper(this);
String favorites [] = myDbHelper.getFavourites();
if(list.size() > 0)
{
list.removeAll(list);
}
for(int i = 0;i < favorites.length; i++)
{
String quotes = favorites[i];
String[] quoteArray = quotes.split(":");
HashMap<String,String> temp[] = null;
temp[i] = new HashMap<String,String>();
temp[i].put("Author",(quoteArray[2]));
temp[i].put("Quote",(quoteArray[4]));
list.add(temp[i]);
}
}
Any help would be greatly appreciated.
Look at this code:
HashMap<String,String> temp[] = null;
temp[i] = new HashMap<String,String>();
You've just assigned a null value to the temp variable (which would more typically have a declaration of HashMap<String, String>[] temp) - so of course you'll get a NullPointerException when you then try to access temp[i] on the very next statement.
It's not clear why you're using an array at all in that code - why aren't you just using:
HashMap<String, String> map = new HashMap<String, String>();
map.put("Author", quoteArray[2]);
map.put("Quote", quoteArray[4]);
list.add(map);
Additionally it's unclear why you're using a map at all here, given that it will always have the same two keys. Why not create a Quote class with name and author properties? Also, using a static variable here seems like a bad idea - why doesn't getFavorites create a new list on each invocation, and return it at the end of the method?
You are declaring and using temp wrong. You don't need an array of HashMap, just a single HashMap, since list is an ArrayList<HashMap>:
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Author",(quoteArray[2]));
temp.put("Quote",(quoteArray[4]));
list.add(temp);
temp doesn't point to an array. You are setting it to null.
You declared the variable temp as an array (by writing HashMap temp[]).
Without being it an actual array, you can't set any elements.
I have a weird problem that I don't fully understand how to solve. Could someone please give me some pointers on hashmaps?
I have a variable:
/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple"
I basically want 10.21,12.12,43.12,12.10 to be associated with blue,red,green,purple (in the order displayed)
In python I created a method that does this with:
def stripChart(name):
name = str(name)
name = urlparse.urlparse(name)
name = cgi.parse_qs(name.query)
name = dict(zip( name['static_labels'][0].split(','), name['static_xvalues'][0].split(',')))
Not sure how to do this in java. So far I have:
URL imgURL = new URL (imgTag);
String[] result = imgURL.getFile().split("&");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
This gives me:
chart_width=288
chart_height=160
chart_type=png
chart_style=manufund_pie
3DSet=true
chart_size=small
leg_on=left
static_xvalues=10.21,12.12,43.12,12.10,
static_labels=blue,red,green,purple,
At this point I'm confused how to link static_labels and static_xvalues values.
Thanks so much. Any pointers would be awesome.
You want to look at StringTokenizer
Something like this (assuming you stored the labels into the String 'static_labels' and the values in the String 'static_xvalues'):
HashMap<String, Double> colorMap = new HashMap<String, Double>();
StringTokenizer labelTok = new StringTokenizer(static_labels, ",");
StringTokenizer valuesTok = new StringTokenizer(static_xvalues, ",");
while(labelTok.hasMoreElements()){
assert(valuesTok.hasMoreElements());
colorMap.put(labelTok.nextElement(), Double.parseDouble(valuesTok.nextElement()));
}
Look at using java.util.HashMap. Let's say you have stored the static_xvalues and static_labels request parameters into corresponding string variables. Something like the following will create the mapping for you:
String[] vals = static_xvalues.split(",");
String[] labels = static_labels.split(",");
HashMap<String,String> map = new HashMap<String,String>();
for (int i=0; i < vals.length; ++i) {
map.put(labels[i], values[i]);
}
You do not say if the xvalues need to be stored as floats or not. If so, you will need to convert the vals array into a Float (or Double) array first, and modify the HashMap instantiation accordingly:
HashMap<String,Float> = new HashMap<String,Float>();