I want to create a lot of instance in a loop but when ı try to String concatenation to generate unique name Java does not permit the operation.My opinion is here
for (Classroom classTmp : classrooms)
{
String s = "sessionClassroom" + count;
SessionClassroom s = new SessionClassroom(classTmp);
}
How can ı generate unique names to create SessionClassroom objects?Thanks for your help.
The error you are getting is because the objects are called the same:
String s = "sessionClassroom" + count;
SessionClassroom s = new SessionClassroom(classTmp);
The problem is that they are both called s. The concatenate operation ("sessionClassroom" + count) is perfectly correct.
In order to solve this problem you should rename either String s or SessionClassroom s to use a different name. Example:
String s = "sessionClassroom" + count;
SessionClassroom sc = new SessionClassroom(classTmp);
EDIT:
If what you want is having as many SessionClassroom values accessible from outside your for loop as the number of classrooms (count), then you should use a data structure like a List:
List<SessionClassroom> list = new ArrayList<SessionClassroom>();
for (Classroom classTmp : classrooms)
{
String s = "sessionClassroom" + count;
list.add(new SessionClassroom(classTmp));
}
You should use a map to hold the sessions if you want to access them by name:
Map<String, ClassroomSession> classroomSessions = new TreeMap<String, ClassroomSession>();
int count = 0;
for (Classroom classTmp: classrooms) {
count++;
String name = "sessionClassroom" + count;
SessionClassroom s = new SessionClassroom(classTmp);
classroomSessions.put(name, s);
}
Then to get access to sessionClassroom3, for instance:
classroomSessions.get("sessionClassroom3").doSomething();
Depending on how you want to access the members, it's probably best to store it as an ArrayList.
Something like
ArrayList<SessionClassroom> lSessions = new ArrayList<SessionClassroom>();
then in the loop put
lSessions.add(new SessionClassroom(classTmp));
It depends a lot on how you want to access the sessions.
Related
for example, I have a list of integer variables
int CLUTCH_CASE = 8;
int CS20 = 6;
int DANGER_ZONE_CASE = 6;
int TOTAL_CASE = 0;
I have an array:
int CaseValue[] = {CS20, CLUTCH_CASE, DANGER_ZONE_CASE};
and I output the value of total cases, which is going to be:
for (int counter=0;counter<CaseValue.length;counter++) {
TOTAL_CASE += CaseValue[counter];
}
System.out.println("You have "+CaseValue.length+" CSGO Cases");
System.out.println("You have a total of "+TOTAL_CASE+" CSGO Cases:");
Output:
You have 3 CSGO Cases
You have a total of 20 CSGO Cases:
yet I also want to output the name.
Example:
(CASENAME are just placeholders for this example. I wanted to use CaseValue[].NAME even that does not exist since it's an example)
for (int counter2=0;counter2<CaseValue.length;counter2++) {
System.out.println(CASENAME+": "+CaseValue[counter2]);
}
My expected and wanted output to be:
CLUTCH_CASE: 8
CS20: 6
DANGER_ZONE_CASE: 6
Is there any way to output the name of the integer variable?
There is no command in Java to access the variable name.
You could use a map (like stated in other answers), but I'd also like to present a simple possibility that is possible without advanced features of Java.
What you could do is the following:
String[] caseName = {"CS20", "CLUTCH_CASE", "DANGER_ZONE_CASE"};
After that you can do:
for (int i=0; i<CaseValue.length; i++) {
System.out.println(caseName[i] + ": " + CaseValue[i]);
}
Use a Map.
Map<String, Integer> ma = new Hashmap()
for (int counter=0;counter<CaseValue.length;counter++) {
TOTAL_CASE += CaseValue[counter];
ma.put(<your_key>, <your_value>)
}
I still dont understand your code completely. So cannot give you a full working snippet. I have however added a snippet on how you could possibly use a map. Store the key as the name that you want and its corresponding value in that key of the map.
You need to use java.lang.Class and its getFields() method to return an array of java.lang.reflect Field[] class object
Below will give you an idea of how, go take a look in the API docs for a better more suitable set of methods to design the process with a List or Set to use contains() method so you can put it in a class and call when you want in a program.
import java.lang.Class;
import java.lang.reflect.*;
Field[] varFset = ((java.lang.Class)this).getFields();
// compare names processing code over the array here
String varname = varFset[x].getName();
You could use a HashMap.
enum CaseType {
CLUTCH_CASE,
CS20,
DANGER_ZONE_CASE;
}
Map<CaseType, Integer> map = new HashMap<>(3);
map.put(CaseType.CLUTCH_CASE, 8);
map.put(CaseType.CS20, 6);
map.put(CaseType.DANGER_ZONE_CASE, 6);
map.forEach((key, value) -> System.out.println(key.name() + ": " + value));
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"));
}
I have a list with some strings in it:
GS_456.java
GS_456_V1.java
GS_456_V2.java
GS_460.java
GS_460_V1.java
And it goes on. I want a list with the strings with the highest value:
GS_456_V2.java
GS_460_V1.java
.
.
.
I'm only thinking of using lots of for statements...but isn't there a more pratical way? I'd like to avoid using too many for statements...since i'm using them a lot when i execute some queries...
EDIT: The strings with the V1, V2,.... are the names of recent classes created. When someone creates a new version of GS_456 for example, they'll do it and add its version at the end of the name.
So, GS_456_V2 is the most recent version of the GS_456 java class. And it goes on.
Thanks in advance.
You will want to process the file names in two steps.
Step 1: split the list into sublists, with one sublist per file name (ignoring suffix).
Here is an example that splits the list into a Map:
private static Map> nameMap = new HashMap>();
private static void splitEmUp(final List names)
{
for (String current : names)
{
List listaly;
String[] splitaly = current.split("_|\\.");
listaly = nameMap.get(splitaly[1]);
if (listaly == null)
{
listaly = new LinkedList();
nameMap.put(splitaly[1], listaly);
}
listaly.add(current);
}
Step 2: find the highest prefix for each name. Here is an example:
private static List findEmAll()
{
List returnValue = new LinkedList();
Set keySet = nameMap.keySet();
for (String key : keySet)
{
List listaly = nameMap.get(key);
String highValue = null;
if (listaly.size() == 1)
{
highValue = listaly.get(0);
}
else
{
int highVersion = 0;
for (String name : listaly)
{
String[] versions = name.split("_V|\\.");
if (versions.length == 3)
{
int versionNumber = Integer.parseInt(versions[1]);
if (versionNumber > highVersion)
{
highValue = name;
highVersion = versionNumber;
}
}
}
}
returnValue.add(highValue);
}
return returnValue;
}
I guess you don't want simply the lexicographic order (the solution would be obvious).
First, remove the ".java" part and split your string on the character "_".
int dotIndex = string.indexOf(".");
String []parts = split.substring(0, dotIndex).split("_");
You are interested in parts[1] and parts[2]. The first is easy, it's just a number.
int fileNumber = Integer.parseInt(parts[1]);
The second one is always of the form "VX" with X being a number. But this part may not exist (if it's the base version of the file). In which case we can say that version is 0.
int versionNumber = parts.length < 2 ? 0 : Integer.parseInt(parts[2].substring(1));
Now you can compare based on these two numbers.
To make things simple, build a class FileIdentifier based on this:
class FileIdentifier {
int fileNumber;
int versionNumber;
}
Then a function that create a FileIdentifier from a file name, with logic based on what I explained earlier.
FileIdentifier getFileIdentifierFromFileName(String filename){ /* .... */ }
Then you make a comparator on String, in which you get the FileIdentifier for the two strings and compare upon FileIdentifier members.
Then, to get the string with "the highest value", you simply put all your strings in a list, and use Collections.sort, providing the comparator.
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 have an XML array that I access to pull a random question from. How would I go about making sure there is no duplicates pulled? My current code follows.
private void getQuestion() {
// TODO Auto-generated method stub
res = getResources();
qString = res.getStringArray(R.array.questions);
rQuestion = qString[rgenerator.nextInt(qString.length)];
tokens = new StringTokenizer(rQuestion, ":");
wordCount = tokens.countTokens();
sep = new String[wordCount];
wArray = 0;
while (tokens.hasMoreTokens()) {
sep[wArray] = tokens.nextToken();
wArray++;
}
}
Any help would be appreciated.
The Fisher-Yates shuffle is an algorithm that is more or less designed for this purpose.
You are better off putting that array of questions in a list and use Collections.shuffle(). After that, simply iterate through the list. More information can be found at this related answer.
This solution will cost some memory for duplicating the list, but remember that the strings themselves won't be copied, only the references to the questions are. For maximum performance, use a list with random access (ArrayList), or use that as a replacement for the array. If you don't theshuffle method will create one internally.
If you want a fast way of getting only unique values from an array this link has a very fast method. Below uses an ArrayList, but it will not be hard for you to convert from string array to an ArrayList - or just use ArrayLists instead.
e.g. new ArrayList(Arrays.asList(myArray));
In short you use a hashset to only get unique values using this method
public static ArrayList GetUniqueValues(Collection values)
{
return new ArrayList(new HashSet(values));
}
Then use it like so
ArrayList x = new ArrayList();
x.add("abc");
x.add("abc");
x.add("abc");
x.add("def");
x.add("def");
x.add("ghi");
for (Object y : GetUniqueValues(x))
Log.d("something", y); //ok lets print the value
To yield the result of "abc, def, and ghi"
To be clear I agree with Travis to ask why you have duplicates. The above is to answer the question.
I figured it out. I switched it to
private void getQuestion() {
res = getResources();
qString = res.getStringArray(R.array.questions);
arrayLength = qString.length;
qTotal = arrayLength;
}
private void getRandom() {
rnd = rgenerator.nextInt(arrayLength);
rQuestion = qString[rnd];
qString[rnd] = "used";
seperate();
}
private void seperate() {
if (rQuestion != "used") {
tokens = new StringTokenizer(rQuestion, ":");
wordCount = tokens.countTokens();
sep = new String[wordCount];
wArray = 0;
while (tokens.hasMoreTokens()) {
sep[wArray] = tokens.nextToken();
wArray++;
}
qNumber++;
} else {
if (qNumber < qTotal) {
getRandom();
} else {
startActivity(new Intent("com.example.END"));
}
}
}
It gets the array from resources, then pulls a random question from the array. It then sets that one to "used" and splits it. It also checks to see if the pulled question is "used, and if it is, it pulls another question. It also goes to the end game activity if all questions are "used"