Separating an argument string into double java - java

So I'm trying to develop a method using String.split and Double.parseDouble and i really need some help! I am relatively new to programming. I'm using Java.
Anyhow, this method interprets a sequence of numbers separated by commas to produce an array of Strings, then it parses each of the strings to get a double, then stores them in sequence.
So far I've managed to separate the String arguments into individual lines:
public class Sequence
{
...
public Sequence(String a)
{
for (String returnvalue: s.split(",")){
System.out.println(returnvalue);
}
}
...
}
At this point i am just so lost! However i do have each of the Strings seperated into individual lines. From here i just have to use the parser to convert the Strings into Doubles and store them in sequence.
Any help would be greatly appreciated! Thank you!
Also, does anyone know where i could learn more about Java programming? I am stuck for resources.

Well, the split() method returns an array. You're looping through it fine, so all you need to do is parse each string into a double for each loop iteration to get an array of doubles:
String[] tokens = s.split(",");
double[] result = new double[tokens.length];
int i = 0; // This is used for putting each double in the array
for(String token:tokens) {
result[i++] = Double.parseDouble(token);
}

Create List like:
String[] array = a.split(",");
List<Double> doubleList = new ArrayList<>(array.length);
for (String token : array) {
doubleList.add(Double.valueOf(token));
}

Related

type casting a String to Object[][]

I would like to convert below String to simple two dimensional array (Object[][]).
String personArray ="{{Melroy,25,India},{Jack,26,USA}}"; // nothing but a simple string with appearance of a 2D array
Can this be done in the first place?
If so what is the simplest way?
Any help any inputs will be greatly appreciated.
Starting from beginning, identify format of your data structure,
seems like your inner array have format {String, Number, String}, to find it, we will create simple regular expression \\{([A-Za-z]+),([0-9]+),([A-Za-z]+)\\}
to make it work properly, you might need to add few modifications, but bellow code will work for your small case
String personArray ="{{Melroy,25,India},{Jack,26,USA}}";
Pattern pattern = Pattern.compile("\\{([A-Za-z]+),([0-9]+),([A-Za-z]+)\\}");
Matcher matcher = pattern.matcher(personArray);
List<Object[]> list = new ArrayList<>();
//using list as we don't know number of final elements,
int start = 0;
while(
matcher.find(start)){
list.add(new Object[]{matcher.group(1),matcher.group(2),matcher.group(3)});
start = matcher.end();
}
//convert to array, to have required format
Object[][] array = list.toArray(new Object[0][]);
//test result
for (Object[] arr : array)
System.out.println(Arrays.toString(arr));

Determining if a given string of words has words greater than 5 letters long

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)

Java String to Float

I am attempting to turn an array list of strings into an arraylist of floats. I have declared the two as such:
ArrayList<Float> AFFloat = new ArrayList<Float>();
ArrayList<String> AFUni0 = new ArrayList<String>();
AFUni is an array list that was parsed from a file. It holds values such as:
[0.059, 0.059, 0.029, 0.412, 0.029, 0.452, 0.386, 0.432, 0.114,0.318, 0.159,0.045, 0.432, 0.477, 0.045...]
I am trying to make those string values into actual numeric values with this set of code:
for (String wntFl:AFUni0){
AFFloat.add(Float.valueOf(wntFl));
}
But for some reason it isn't working. It is coming back with this error:
java.lang.NumberFormatException: For input string: "0.114,0.318"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Float.valueOf(Float.java:388)
at allelefreq.AlleleFreq.main(AlleleFreq.java:122)
Does anyone know why this is happening?
Thanks
It looks like some values are separated by ", " while others, like your example, only by ",". This could be the reason for the failed recognition.
The answer is in your Exception
java.lang.NumberFormatException: For input string: "0.114,0.318"
You pass the "0.114,0.318" as wntFl, that is why you have NUmberFormatException
You should assure that your input is valid.
First you should split the input, then you can parse it.
As the error message shows you, the value it's failing on is "0.114,0.318" (i.e., NOT "0.114" or "0.318", but multiple numbers in one String), which is not a valid number. However you're populating your ArrayList, you're getting multiple values in a single String. You can fix this by fixing the code that populates the array or using String.split(",") to get an array of the values and loop over that before casting to floats.
0.114,0.318 is not a valid float (Observe ,in between), that is whyNumberFormatException`
You may need to first split() the string which returns array and then pass values to Float.valueOf(str[i])
Separators are not quite constant in all string-stream. Try to find problem in this way.
you should use String.split(",") because 0.114,0.318 is not a valid float
You don't do the splitting correctly.
This kind of project works very well (but its just example)
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Float> floats = new ArrayList<Float>();
ArrayList<String> strings = new ArrayList<String>();
strings.add("0.123");
strings.add("1.123");
strings.add("0.423");
strings.add("34.423");
strings.add("0.000");
for(String str : strings) {
floats.add(Float.valueOf(str));
}
for(Float fl : floats) {
System.out.println(fl);
}
}
This could be the reason of Internationalization/Localization, In many languages . is replaced with ,/،
Just like in Spanish http://translate.google.com/#auto/es/10.1
Or in Arabic http://translate.google.com/#auto/ar/10.1.
You have to take care of localization in case of string to float conversion.

How to take numbers from a string and put them into an arrayList

I have a program that I am trying to take a set of numbers from a string separated by commas and place them into an ArrayList; however, I'm not quite sure how to do it. So far what I have done is turn the String into an array of chars and then convert the chars into ints by using:
Character.digit(temp[i], 10)
This example is in a for loop iterating over a string. Let's say in this case "1,2,3,4". taking the first element of the new char array and converting it to a int.
My issue is,
A: there has to be a better way of doing this.
B: what happens if you get a 2 or three digit number instead, e.g, "34,2,3,65,125". these will be stored as separate elements of the array when i need it to be one element.
C: what happens if the number is a negative one, and what if that negative number is 2 or three digits long? E.g., "-123,45,3,4,-6".
Remember that this is mean to be for any String argument.
There are lots of conditions here and I'm not sure how to solve them.
Consider using
String.split() http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Integer.parseInt() http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html
Regarding "any String argument," you have a choice: either fail on the strings which are not comma-separated numbers or redefine the task. Here comes the essence of the programming: you need to define everything. The easiest way (and the safest, usually) is to fail whenever you see something unexpected. Java will do it for you in this case, so enjoy.
you could just do:
String input = "-12,23,123123";
String[] numbers = input.split(",");
List<Integer> result = new ArrayList<Integer>();
for(String number : numbers){
result.add(Integer.parseInt(number));
}
Use the String.split() function to break your String in different strings, based on the separator:
String input="-123,45,3,4,-6";
String[] vals=input.split(",");
List<Integer> numbers=new ArrayList<Integer>(vals.length);
for(String val:vals) {
numbers.add(Integer.valueOf(val));
}
First split the input String using String.split(). Then try Integer.parseInt().
String testStr = "123,456,789";
String tokens[] = testStr.split(",");
ArrayList<Integer> numList = new ArrayList<Integer>();
for(int i = 0; i < tokens.length; i++)
{
try
{
Integer num = new Integer(tokens[i]);
numList.add(num);
}
catch(NumberFormatException e)
{
//handle exception
}
}
String input="-123,45,3,4,-6, a";
String[] vals=input.split(",");
List<Integer> numbers=new ArrayList<Integer>(vals.length);
for(String val:vals) {
try {
int a = Integer.valueOf(val);
numbers.add(a);
} catch (NumberFormatException e) {
// TODO: handle exception
}
}
Use this code. By using it you can also avoid non-integer values if there any.
You can also use StringTokenizer to split the string into substrings, and then use Integer.parseInt to convert them into integers.

Splitting string N into N/X strings

I would like some guidance on how to split a string into N number of separate strings based on a arithmetical operation; for example string.length()/300.
I am aware of ways to do it with delimiters such as
testString.split(",");
but how does one uses greedy/reluctant/possessive quantifiers with the split method?
Update: As per request a similar example of what am looking to achieve;
String X = "32028783836295C75546F7272656E745C756E742E657865000032002E002E005C0"
Resulting in X/3 (more or less... done by hand)
X[0] = 32028783836295C75546F
X[1] = 6E745C756E742E6578650
x[2] = 65000032002E002E005C0
Dont worry about explaining how to put it into the array, I have no problem with that, only on how to split without using a delimiter, but an arithmetic operation
You could do that by splitting on (?<=\G.{5}) whereby the string aaaaabbbbbccccceeeeefff would be split into the following parts:
aaaaa
bbbbb
ccccc
eeeee
fff
The \G matches the (zero-width) position where the previous match occurred. Initially, \G starts at the beginning of the string. Note that by default the . meta char does not match line breaks, so if you want it to match every character, enable DOT-ALL: (?s)(?<=\G.{5}).
A demo:
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}
which can be tested online here: http://ideone.com/q6dVB
EDIT
Since you asked for documentation on regex, here are the specific tutorials for the topics the suggested regex contains:
\G, see: http://www.regular-expressions.info/continue.html
(?<=...), see: http://www.regular-expressions.info/lookaround.html
{...}, see: http://www.regular-expressions.info/repeat.html
If there's a fixed length that you want each String to be, you can use Guava's Splitter:
int length = string.length() / 300;
Iterable<String> splitStrings = Splitter.fixedLength(length).split(string);
Each String in splitStrings with the possible exception of the last will have a length of length. The last may have a length between 1 and length.
Note that unlike String.split, which first builds an ArrayList<String> and then uses toArray() on that to produce the final String[] result, Guava's Splitter is lazy and doesn't do anything with the input string when split is called. The actual splitting and returning of strings is done as you iterate through the resulting Iterable. This allows you to just iterate over the results without allocating a data structure and storing them all or to copy them into any kind of Collection you want without going through the intermediate ArrayList and String[]. Depending on what you want to do with the results, this can be considerably more efficient. It's also much more clear what you're doing than with a regex.
How about plain old String.substring? It's memory friendly (as it reuses the original char array).
well, I think this is probably as efficient a way to do this as any other.
int N=300;
int sublen = testString.length()/N;
String[] subs = new String[N];
for(int i=0; i<testString.length(); i+=sublen){
subs[i] = testString.substring(i,i+sublen);
}
You can do it faster if you need the items as a char[] array rather as individual Strings - depending on how you need to use the results - e.g. using testString.toCharArray()
Dunno, you'll probably need a method that takes string and int times and returns a list of strings. Pseudo code (haven't checked if it works or not):
public String[] splintInto(String splitString, int parts)
{
int dlength = splitString.length/parts
ArrayList<String> retVal = new ArrayList<String>()
for(i=0; i<splitString.length;i+=dlength)
{
retVal.add(splitString.substring(i,i+dlength)
}
return retVal.toArray()
}

Categories