I have an array, which may differ in content based on some user selections.
One of the arrays look like this:
String[] get_elements = { "firstname", "lastname", "address", "status" };
In a static function, to get what I need to end up with, I would do this:
String name = c.getString(JSON_NAME);
String address = c.getString(JSON_ADDRESS);
String status = c.getString(JSON_STATUS);
Now, what I want to do, is set a string, based on what the content of the array is, like this:
for (int x = 0; x < get_elements.length; x++) {
String get_elements[x] = c.getString(get_elements[x]);
}
The array consists of: firstname, lastname, address and status.
So i want to end up with a loop-defining them as strings and assigning values to those strings, ending up with rawcode:
string firstname = c.getString("firstname");
And so on. I've tried using String get_elements[x] = c.getString(get_elements[x]) with no luck.
Is there a way to dynamically create strings based on the array content?
No, You can't. The way you tried with array is the something you can try similar to this.
String[] elements=new String[4];
for (int x = 0; x < get_elements.length; x++) {
elements[x] = c.getString(get_elements[x]);
}
You are replacing the existing element in array. Instead try this:
String result_elements = new String[get_elements.length];
for (int x = 0; x < get_elements.length; x++) {
result_elements[x] = c.getString(get_elements[x]);
}
Hope it solves your issue.
You cannot build an execute new java code at runtime. Besides, what would be the point of a single String firstname that contains c.getString("firstname") without any further information? You are better to use c.getString("firstname") where you need that sole return value.
You have to posses information about what data corresponds to what index. Take the name "Carter" as an example in addition to the fact, that the number of indices in the array may vary based on the user's choice. How are you going to examine, if "Carter" is the firstname or the lastname?
Related
I need your help. I have a string with value "1,2,3,4,5,6,7,8,9,10".
What I want to do is take once first value ("1") only (substring (0, 1) for example) and then do a loop with the rest of values except the first value that I already take.
Maybe I have to create another String variable and set the values without first value to the second String variable and then create a loop? How to do that?
The easiest way would probably be to use String#split(String):
String str = "1,2,3,4,5,6,7,8,9,10";
String[] parts = str.split(",");
// Save the first part
String firstPart = parts[0];
// Iterate over the others:
for (int i = 1; i < parts.length; ++i) {
System.out.println (parts[i]); // Or do something useful with it
}
You can use split function.
String numbers = "1,2,3,4,5,6,7,8,9,10"; //Here your String
String[] array = numbers.split(","); //Here you divide the String taking as reference the ,
String number = array[0] //You will get the number 1
If you want to take the rest of the elements:
for(i = 1; i < array.length; i++)
System.out.println(array[i]);
I expect it will be helpful for you!
I've got some text files I need to extract data from. The file itself contains around a hundred lines and the interesting part for me is:
AA====== test==== ====================================================/
AA normal low max max2 max3 /
AD .45000E+01 .22490E+01 .77550E+01 .90000E+01 .47330E+00 /
Say I need to extract the double values under "normal", "low" and "max". Is there any efficient and not-too-error-prone solution other than regexing the hell out of the text file?
If you really want to avoid regexes, and assuming you'll always have this same basic format, you could do something like:
HashMap<String, Double> map = new HashMap<>();
Scanner scan = new Scanner(filePath); //or your preferred input mechanism
assert (scan.nextLine().startsWith("AA====:); //remove the top line, ensure it is the top line
while (scan.hasNextLine()){
String[] headings = scan.nextLine().split("\\s+"); //("\t") can be used if you're sure the delimiters will always be tabs
String[] vals = scan.nextLine().split("\\s+");
assert headings[0].equals("AA"); //ensure
assert vals[0].equals("AD");
for (int i = 1; i< headings.length; i++){ //start with 1
map.put(headings[i], Double.parseDouble(vals[i]);
}
}
//to make sure a certain value is contained in the map:
assert map.containsKey("normal");
//use it:
double normalValue = map.get("normal");
}
Code is untested as I don't have access to an IDE at the moment. Also, I obviously don't know what's variable and what will remain constant here (read: the "AD", "AA", etc.), but hopefully you get the gist and can modify as needed.
If each line will always have this exact form you can use String.split()
String line; // Fill with one line from the file
String[] cols = line.split(".")
String normal = "."+cols[0]
String low = "."+cols[1]
String max = "."+cols[2]
If you know what index each value will start, you can just do substrings of the row. (The split method technically does a regex).
i.e.
String normal = line.substring(x, y).trim();
String low = line.substring(z, w).trim();
etc.
I am learning Java and looking for a comprehensive code of multiplying the elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of strings and the second is integers?
I'm afraid Java isn't going to support this kind of thing natively, and you'll need to perform some of your own logic to implement it. Let's say you've got your String[]..
String[] a = {"a", "b", "c", "d"};
And you've got your int[]..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a StringBuilder, then you'll import it and declare..
StringBuilder total = new StringBuilder();
NOTE: StringBuilder is strongly recommended here.
And then you're looping multiplier amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of a[x] to the repeated String.
NOTE: Something that's also important is leaning good practise. If you're using Java code, it's considered terrible practise to repeatedly concatenate String objects. StringBuilder is more efficient, and is the Java standard. I would strongly recommend using this.
Have fun putting it all together!!
To create string filled with multiple instances of same character like "ccc" you can firs create array of characters which will hold only 3 characters like
char[] myCharacters = new char[3];
Now this array is filled with zeroes ('\0'), so you need to fill it with desired character 'c'. You simply do it using for loop
for (int i = 0; i<myCharacters; i++){
myCharacters[i] = 'c';
}
After this your array will contain ['c', 'c', 'c'].
Now you can use this array to create string using characters from it. To do so you just need to pass this array to String constructor like
String myString = new String(myCharacters);
And there you go. Now you have "ccc" String. Repeat these steps for each pair of elements from a and b arrays.
You can also use shorter version which kinds of do the same
String myString = new String(new char[3]).replace('\0','c');//will produce "ccc"
I've got a question about making a save function.
I'm trying to have a string be saved as a single file to set specific settings on a game. So saveFile would read "002007...", having 002 be a player's location, then 007 a player's level, for example.
I understand how to compile the various variables into a single string, but how would I return it to individual variables?
You better go with SQLite or SharedPreferences if you really want to save settings for a game on Android.
On the other hand, if you have to stick with saving a String on a file, you might want to use a delimiter(ie \r\n or # or | would do it) between numbers. So while parsing back delimiters will help you a lot, but beware when things get complicated a single String won't do the thing nicely. Then you might want to use JSON (for simplicity I would prefer gson) to encode your settings into one String and vice verse.
You could use a delimiter between the values like this:
int location = 02;
int level = 3;
int powerUps = 46;
... and so on
String saveString = location + "#" + level + "#" + powerUps + "#" + ...
Then to load the String back into variables:
String[] values = saveString.split("#");
location = values[0];
level = values[1];
powerUps = values[2];
... and so on
My advice is to check out Shared Preferences and you can read Android's documentation on it here.
If you did want to use your single String, file method, I suggest using delimiters. That simply means to put commas, or other types of delimeters in between different integer values. Instead of "002007", save it as "002,007". Example:
String s = "002,007"
String[] values = s.split(","); // values[0] is "002" and values[1] is "007"
Using the .split(String) command will return a String array with each element in the array containing parts of the String that was split up by the parameter, in this case: ,
If you wanted to separate values per person, something like this could be done:
String s = "002,007;003,008";
String[] people = s.split(";"); // people[0] is "002,007", people[1] is "003,004"
String[][] person = new String[people.length][people[0].split(",").length];
for (int i = 0; i < people.length; i++)
{
person[i] = people[i].split(",");
}
Here is what the array would then contain:
person[0][0] is "002"person[0][1] is "007" person[1][0] is "003" person[1][1] is "008"
// print it for your own testing
for (String ppl[] : person)
{
for (String val : ppl)
{
System.out.print(val + " ");
}
System.out.println("");
}
So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒ You might want to use: +=
⇒ You might want to use: ==
⇒ You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)