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.
Related
I have been trying to take the array input by separating the values with '#'.Can anyone of you help me to get through this?
I have used the split function but it is not working. Is there any possibility of solving this problem?
Take your and start appending it to String then:
StringBuffer str;
//loop it
str.append(arr[i])
String[] arrOfStr = str.split("#");
After that convert to Integer and use
Take user input for 5 times, store them in a variable and display all 5 values in last. How can I do this in Java? Without using arrays, collections or database. Only single variable like String and int.
Output should look like this
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
This seems like a needless exercise in futility, but I digress...
If you want to store them in a single string, you can do it like so:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
if you then input foo bar baz storageString will contain foo;bar;baz;. (in.next() will read the input strings to the spaces, and in.hasNext() returns false at the end of the line)
As more strings are input, they are appended to the storageString variable. To retrieve the strings, you can use String.split(String regex). Using this is done like so:
String[] strings = storageString.split(";");
the strings array which is retrieved here from the storageString variable above should have the value ["foo", "bar", "baz"].
I hope this helps. Using a string as storage is not optimal because JVM creates a new object every time a string is appended onto it. To get around this, use StringBuilder.
*EDIT: I originally had said the value of the strings array would be ["foo", "bar", "baz", ""]. This is wrong. The javadoc states 'Trailing empty strings are therefore not included in the resulting array'.
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
Why dont you use Stingbuilder or StringBuffer, keep appending the some delimiter followed by the input text.
Use simple String object and concatenate it with new value provided by user.
String myString = "";
// while reading from input
myString += providedValue;
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));
}
Write a static function that takes a string as an argument and returns
the third word in the string. Call the function with the following
string:
This is my string
Print the result to the console.
New to java and having a hard time figuring this problem at (new at java). Im not sure how to approach the problem. Ive figured out how to get the results with an array but is an array even a possible answer? What im having trouble with most is the returning of the 3rd word of the string.
edit:
Heres what I have currently to figure what was asked for, just not sure if its correct
public class problem4 {
public static void main(String[] args) {
String[] str;
str = strArray();
System.out.println(str[2]);
}
public static String[] strArray(){
String[] array = {"This", "is", "my", "string"};
return array;
}
}
This is on the right track, but its not exactly what the problem is asking for.
You are missing two big things here. First, you need to put this into a static function that takes a string (meaning you have to make your own, you cant use main). That would look something like this -
public static String getThirdWord(String s){
Second, your logic works assuming you get a String array. The problem though states you are getting a String. That means you have to do some work before you can use your (mostly correct) array notation. Here is what you need
String[] words = s.split(" ");
This will take the input, and 'split' it into parts around the spaces. You are essentially getting back an array of the individual words.
Then you can start using the array notation -
return words[2];
HOWEVER: you might get an input that is less than three words! This would cause an exception to be thrown when you do words[2]. Your problem does not state what to do in such a case, but you will almost certinally need to check the size by doing if(words.size>2)
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.