Got this code (not working):
for (int i = 0; i < splitSource.length; i++) {
float[] nr = Float.parseFloat(splitSource[i]);
}
I have an collection of strings...
List<String> stringCollection = new ArrayList<>();
Previously, every string from the list is treated separately extracting from it the necessary and unnecessary characters and the final result is a string of pure numbers.
Now, I need to convert those numbers from String into Float, but i get the error of "float cannot be converted to float[]"...
float[] nr= new float[splitSource.length];
for (int i = 0; i < splitSource.length; i++) {
nr[i] = Float.parseFloat(splitSource[i]);
}
Float.parseFloat returns single float number, not array. Also, declaring float[] nr inside for cycle makes no sense. Result will be lost when cycle ends.
The method Float.parseFloat(String) delivers a float. Not an array of float. So just write
float[] nr = new float[splitSource.length];
for(...) {
nr[i] = Float.parseFloat(splitSource[i]);
}
Related
I have to get an float[] array from an TockaXY[] array.
Example of TockaXY[] with 4 elements:
[60.039005,86.44917][96.53153,41.086178][19.988914,31.67395][96.84925,41.90731]
but I need an float[]. Tried:
for (int i = 0; i < objectArray.length; i++)
floatArray[i] = (Float)objectArray[i];
But I get error cannot Cast.
Any Ideas?
If i understood it right, you have an array within an array.
if you want to keep it this way than you have to create another array within an array
so;
float floatArray[][]; //declare a 2D array
floatArray = new float[4][2]; //make it's length same as yours
for (int i = 0; i < objectArray.length; i++){
for(int j =0; j<objectArray[i].length; j++){
//parse each value as float, and assign it to your new array
floatArray[i][j] = Float.parseFloat(objectArray[i][j]);
}
}
First of all your given element is not array, its array of array.
You can try this to convert Object[][] to Float[][].
Object[][] objectArray = { { 60.039005, 86.44917 }, { 96.53153, 41.086178 }, { 19.988914, 31.67 },
{ 96.84925, 41.90731 } };
Float[][] floatArray = new Float[objectArray.length][2];
for (int i = 0; i < objectArray.length; i++) {
floatArray[i][0] = ((Double) objectArray[i][0]).floatValue();
floatArray[i][1] = ((Double) objectArray[i][0]).floatValue();
}
System.out.println(floatArray);
Assuming TockaXY is something like
public sclass TockaXY {
private float x;
private float y;
//Constructors, getters, setters etc.
#Override
public String toString() {
return "["+ x + ", " + y + "]";
}
}
and you want a float[] containing the values of x and y from each element of a TockaXY[], the size of the float[] must be 2 * size of TockaXY[].
float [] floatArray = new float[objectArray.length * 2];
for (int i = 0, j=0; i < objectArray.length; i++) {
floatArray[j++] = objectArray[i].getX();
floatArray[j++] = objectArray[i].getY();
}
This: (SomeType) someExpr; is called a cast operation. Unfortunately, there are 3 completely different things that java can do, that all look exactly like this. A real guns and grandmas situation!
Casts can convert things, or can assert generics in types, or can coerce types itself. The latter two, at runtime, do nothing (maybe throw ClassCastException), it's just ways to tell the compiler you know what you are doing; to treat things as different types.
The ONLY one that converts anything is the 'type conversion' mode, and that one only kicks in if both the type in the parentheses and the expression you're applying it on are primitive (auto-unboxing may kick in, but it ends there).
Float is not primitive (float is primitive), so you're not doing a type conversion here, but your question makes it sound like you think you are.
Okay, and.. how do I fix my code?
It looks like TockaXY is a class that looks something like:
class TockaXY {
public float x, y;
}
From your question it is unclear what you want here. Do you want all 8 floats in an 8-sized float array? Do you only want the 'x' elements? Only the 'y' elements?
A TockaXY is not a float (it's a coordinate), so this is not easy, you'd have to program that. For example:
TockaXY[] in = ...;
float[] fs = new float[in * 2];
for (int i = 0; i < in.length; i++) {
fs[i * 2] = in[i].x;
fs[(i * 2) + 1] = in[i].y;
}
I have an array of doubles:
double[] arrayOfDoubles = new double[]{doubleVal1, doubleVal2, doubleVal3, doubleVal4, doubleVal5, doubleVal6};
and doubleValues initialization:
double doubleVal1 = 0;
double doubleVal2 = 0;
double doubleVal3 = 0;
double doubleVal4 = 0;
double doubleVal5 = 0;
double doubleVal6 = 0;
and now im using foreach loop with that array:
for (double val : arrayOfDoubles)
{
val += 0.1;
}
i thinked it should add to every value(doubleVal1, doubleVal2..., doubleVal6) value 0.1.
What should i change to get that?
You can't do that with the advanced for loop, since val contains a copy of a value taken from the array, so modifying it doesn't modify the array.
Use a regular for loop instead:
for (int i = 0; i < arrayOfDoubles.length; i++)
{
arrayOfDoubles[i] += 0.1;
}
Use a regular for loop, not a foreach, so that you can access the indexes of the array .
for (int i = 0 ; i<arrayOfDoubles.length; i++)
{
arrayOfDoubles[i] += 0.1;
}
Also have a look at : Is Java “pass-by-reference” or “pass-by-value”?
You can use foreach like this instead :
int i = 0;
for (double val : arrayOfDoubles) {
arrayOfDoubles[i] += 0.1;
i++;
}
Because for each in reality create a temp variable and not use the real values of array, it work like this
for (int i = 0; i < arrayOfDoubles.length; i++) {
double val = arrayOfDoubles[i];
// ^^---------------------------------for each create a temp variable like this
}
You should change your loop from the enhanced for loop to regular for loop, because loop variable modifications do not reflect on the original item:
for (int i = 0 ; i != arrayOfDoubles.length ; i++) {
arrayOfDoubles[i] += 0.1;
}
Note that this change would still have no effect on the fields doubleVal1..doubleVal6, which are copied into arrayOfDoubles on initialization. You cannot modify these without either referencing them directly, or using reflection (definitely not recommended for this task).
If your ultimate goal is to modify fields doubleVal1..doubleVal6, consider restructuring your class in a way that places these fields into an array permanently.
I guess the point is to change the variables values, not the array's values. But this is not possible with primitives.
You can create a simple class holding the value, but I'm sure there is a better design approach for your task:
class DoubleHolder {
double val;
}
DoubleHolder doubleVal1 = new DoubleHolder();
DoubleHolder doubleVal2 = new DoubleHolder();
DoubleHolder doubleVal3 = new DoubleHolder();
DoubleHolder doubleVal4 = new DoubleHolder();
DoubleHolder doubleVal5 = new DoubleHolder();
DoubleHolder doubleVal6 = new DoubleHolder();
DoubleHolder[] arrayOfDoubles = {doubleVal1, doubleVal2, doubleVal3, doubleVal4, doubleVal5, doubleVal6};
for (DoubleHolder dh : arrayOfDoubles) {
dh.val += 0.1;
}
System.out.print(doubleVal3.val); // prints 0.1
I'm trying to covert an array of strings into an array of doubles.
I'm fairly familiar with ArrayList<>() , but i see there is in an example code give, double[].
example: list = ["1" , "2" , "3"]
desired return: number = [1 , 2 , 3]
public double[] ConversionNumber
{
double[] sequence = new double[list.size()];
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)}
return sequence;
when i do this, i get an error in Bluej compiler: "cannot find symbol- method add(double).
What is a good way to solve this (i'm a beginner at Java).
thanks!
If list is an array, then list.size() would fail. I think we can assume it should be a List<String>. And you access an array by index. Also, I assume it should be an argument to your method. Next, Java convention for methods names is camelCase.
public double[] conversionNumber(List<String> list) {
double[] sequence = new double[list.size()];
int pos = 0;
for (String element : list) {
double val = Double.parseDouble(element);
sequence[pos++] = val; // <-- post-increment
}
return sequence;
}
Generally, if you're working with Collections, you work with collections the whole way. It's bad form to use Lists for one thing, but arrays for another. So it's advisable to do this with a List<Double> instead of a double[]
public List<Double> parseDoubles(List<String> strings) {
List<Double> doubles = new ArrayList<>(strings.size());
for(String string : strings) {
doubles.add(new Double(string));
}
return doubles;
}
Below code will work for your case:
java.util.List<String> list = java.util.Arrays.asList("1", "2", "3");
public double[] ConversionNumber() {
double[] sequence = new double[list.size()];
int i = 0;
for(String element:list){
double val = Double.parseDouble(element);
sequence[++i] = val;
}
return sequence;
}
The error happens because arrays dont have an 'add' method. You will want to do something like:
double[] sequence = new double[list.length];
for(int i = 0; i < list.length; i++){
sequence[i] = Double.parseDouble(list[i]);
}
If list is an actual List not a String[] as I assumed, you would do:
double[] sequence = new double[list.size()];
for(int i = 0; i < list.size(); i++){
sequence[i] = Double.parseDouble(list.get(i));
}
Change your code here
for(String element:list){
double val = Double.parseDouble(element);
sequence.add(val)
}
to this if your list is a List:
for(int i=0;i<list.size();i++){
double val = Double.parseDouble(list.get(i));
sequence[i]=val;
}
if your list is an Array, then change to this:
for(int i=0;i<list.length;i++){
double val = Double.parseDouble(list[i]);
sequence[i]=val;
}
So I need to use the class org.apache.commons.math3.stat.StatUtils to compute the mean of an array of float, but the input array should be an array of double.
How can I convert float[] into a double[]?
You can solve your problem by defining logical steps that all together achieve the goal:
Create a double[] of same length as the float[]
Iterate over the float[] and save the values one by one in the corresponding index in the double[]
Traditionally or pre Java 8 one would go this way:
final double[] doubleArray = new double[floatArray.length];
for (int i = 0; i < floatArray.length; i++) {
doubleArray[i] = floatArray[i]; // no casting needed
}
When using Java 8 you can use the Stream API for this to get a neater solution:
IntStream.range(0, floatArray.length).forEach(index -> doubleArray[index] = floatArray[index]);
Possible use as function:
public static double[] convertToDouble(final float[] values) {
final double[] result = new double[values.length];
IntStream.range(0, values.length).forEach(index -> result[index] = values[index]);
return result;
}
Convert each value in array to double.
Float is shorter than double, so You don't have to worry about losing precision.
Create array of doubles of the same length as float array.
Then, You can implict convert array of float to array of double.
public double[] answer(float[] array){
double[] newArray = new double[array.length];
for ( int i = 0 ; i < array.length ; i++ )
newArray[i] = (double) array[i];
return newArray;
}
I have written some code for sorting random integers that a user inputted. How would I switch this into sorting randomly inputted letters? Aka, user inputs j, s, g, w, and the programs outputs g, j, s, w?
for (int i = 0; i < random.length; i++) { //"random" is array with stored integers
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j] < random[x]) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final int temp = random[i];
random[i] = random[x];
random[x] = temp;
}
itsATextArea.append(random[i] + "\n");// Output ascending order
}
Originally I hoped (though I knew the chances of me being right were against me) that replacing all the 'int' with 'String' would work...naturally I was wrong and realized perhaps I had to list out what letter came before which by using lists such as list.add("a"); etc.
I apologize if this seems like I am asking you guys to do all the work (which I'm not) but I'm not entirely sure how to start going about this, so if anyone can give some hints or tips, that would be most appreciated!
You could use String.compareTo() to do that:
Change this:
int[] random = new int[sizeyouhad];
...
if (random[j] < random[x]) {
...
final int temp = random[i];
to:
String[] random = new String[sizeyouhad];
...
if (random[j].compareTo(random[x]) < 0) {
...
final String temp = random[i];
Trial with your code:
String[] random = new String[3];
random[0] = "b";
random[1] = "c";
random[2] = "a";
int x = 0;
//"random" is array with stored integers
for (int i = 0; i < random.length; i++) {
// Assume first value is x
x = i;
for (int j = i + 1; j < random.length; j++) {
//find smallest value in array (random)
if (random[j].compareTo(random[x]) < 0) {
x = j;
}
}
if (x != i) {
//swap the values if not in correct order
final String temp = random[i];
random[i] = random[x];
random[x] = temp;
}
System.out.println(random[i] + "\n");// Output ascending order
}
If you're just trying to sort a list of strings you should probably use the java.util.Collections.sort method rather than writing your own sorting routine.
Was random originally int[]? If you had changed this to String[], you can use String#compareTo method to discern if one string is "less than" another.
Incidentally, you can change the type of random to Comparable[] and then you can use the same algorithm to sort any object whose class implements the interface!
Try to use Collections.sort() function
List<String> l = Arrays.asList("j","s", "g","w");
Collections.sort(l);
If you consider every character to be a code point[1] and you want to sort by Unicode code point order[2], then there is really no need to change your logic. The work is converting from whatever input you are given (String, char[], etc.) into an int[] of the code points.
[1] - http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#codePointAt(int)
[2] - http://en.wikipedia.org/wiki/Code_point
You can make your code work on any type of Object by using generics.
The following code is very simple and works perfectly (With this library you can solve your problem in few lines):
import static ch.lambdaj.Lambda.sort;
import static ch.lambdaj.Lambda.on;
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
List<String> list = Arrays.asList("1","102","-50","54","ABS");
List<String> newList = sort(list, on(String.class));
System.out.println(newList);//[-50, 1, 102, 54, ABS]
}
}
This code uses lambda library (download here, website). Find in the website this example:
List<Person> sorted = sort(persons, on(Person.class).getAge());