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;
}
Related
I have the following code that I am trying to convert from C++ into Java. The code is supposed to generate a binomial tree that will be used calculate stock option prices.
Here is the following C++ code:
class Price {
public:
double stockPrice;
double optionPrice;
};
int numIntervals = 500;
Price ** binomialTree;
binomialTree = new Price*[numIntervals+1];
for (i = 0; i <= numIntervals; i++) {
binomialTree[i] = new Price[i + 1];
}
for (i = 0; i <= numIntervals; i++) {
for (j = 0; j <= i; j++) {
binomialTree[i][j].stockPrice = sNaught * pow(up, j) * pow(down, i-j);
}
}
I need the java code that will initialize the binomial tree so that I can iterate through it and calculate the various prices. The part that is throwing me off is the binomialTree[i] = new Price[i+1]; which occurs inside the loop, making the 2D array dynamic which you can't do in java. This is what I came up with which runs but the resulting price is incorrect with compared to the values given.
class Price {
double stockPrice = 0.0;
double optionPrice = 0.0;
Price(double sP, double oP) {
this.stockPrice = sP;
this.optionPrice = oP;
}
}
int i,j;
Price[][] binomialTree = new Price[numIntervals+1][numIntervals+2];
for (i = 0; i <= numIntervals; i++) {
for (j = 0; j <= i; j++) {
binomialTree[i][j] = new Price(option.getsNought() * Math.pow(up, j) * Math.pow(down, i-j), 0);
}
}
Two dimensional arrays whose row length is dynamic are very much possible in Java. Since I don't have your entire settings, here is a short example for you:
Price[][] binomialTree = new Price[20][];
for ( int i = 0 ; i < 20 ; i++ ) {
binomialTree[i] = new Price[i+1];
}
for ( int i = 0; i < 20; i ++ ) {
System.out.println( Arrays.toString(binomialTree[i]));
}
The output of this is (since we haven't populated the arrays):
[null]
[null, null]
[null, null, null]
[null, null, null, null]
...
It is worth noting that Java does not have "two dimensional arrays" (in the sense that all dimensions are allocated together as a consecutive chunk of memory) at all. All it has is one-dimensional arrays, whose base type can be a reference type. And the reference type can be that of an array.
A declaration such as
Price[][] arr = new Price[5][7];
is merely syntactic sugar that does the same as creating a 5-element array of references to arrays of Price, then creating 5 arrays of 7 references to Price and assigning them to each element of that first array.
For a formal discussion of this, read the Java Language Specification.
i am new in java programming.I need to convert my matlab code to basic java codes not complex like just using loops and array, i tried several times but i failed.Thanks for helping.Here is my code.
x = [1,2,3,4,5,6,7];
x = perms(x);
i = 0;
c=1;
for m=1:1:5040;
for n=1:1:6;
if(x(c,n) == (x(c,(n+1))-1))
i = i+1;
break
end
end
c=c+1;
end
Answer : 2119
Let us go through the Matlab code and translate each row into Java. We will be going to need some abstractions, which we will introduce on the go.
First line:
x = [1,2,3,4,5,6,7];
A vector is assigned to a variable x. We could simply say that a vector is an array of integers, but maybe we need some better abstractions later. Let us define a new class Vector. Do not confuse it with java.util.Vector: There may be multiple classes of the same unqualified name.
class Vector {
private int[] value;
Vector(int... value) {
this.value = value;
}
int apply(int i) {
return value[i - 1];
}
int length() {
return value.length;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (int entry : value) {
result.append(prefix).append(entry);
prefix = " ";
}
return result.toString();
}
}
We are using an array of integers for the internal representation of our Vector. Note that you can swap out the internal representation any time as long as it does not leak out into the classe's interface. Hence, we restrict the access of our value-member to private, meaning only objects of type Vector are allowed to access it.
New Vector objects are instantiated by calling the constructor Vector(int... value), which takes a vararg integer argument. Internally in Java, varargs are the same as arrays, but they give us syntactic sugar, to instantiate our x in the following way:
Vector x = new Vector(1, 2, 3, 4, 5, 6, 7);
which looks very similar to your Matlab code.
An other thing is that, in Java, arrays are zero-indexed, while Matlab starts indexing at 1. Our Vector class defines an apply-method, which is supposed to access the i-th index. Hence, it returns value[i-1].
Now we want to compute
x = perms(x);
perms returns a matrix, containing all permutations of vector x. So we need an other abstraction: Matrix.
class Matrix {
private Vector[] rows;
Matrix(Vector... value) {
this.rows = value;
}
int apply(int x, int y) {
return rows[x - 1].apply(y);
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
String prefix = "";
for (Vector row : rows) {
result.append(prefix).append(row.toString());
prefix = System.lineSeparator();
}
return result.toString();
}
}
Matrix is defined very similar to Vector, but its internal representation is an array of Vector, the rows of the matrix. Again, we define a method apply to retrieve an element: this time, it takes two parameters, the row index and the column index.
Side note: It is always good to override the method toString which is defined in the top element of Java's type hierarchy: Object. You can try to instantiate a Vector or a Matrix and pass it as argument to System.out.println to see how the string representation looks like.
Now we still need to implement perms in Java. The method perms takes a Vector and returns a Matrix. I have a very hacked and ugly implementation which I am a bit reluctant to show, but for the sake of a complete answer, here it is:
static Matrix perms(Vector vector) {
int[] indices = new int[vector.length()];
for (int i = 0; i < vector.length(); i++)
indices[i] = i;
List<int[]> allPermuationIndices = new ArrayList<int[]>();
permutation(new int[0], indices, allPermuationIndices);
Vector[] perms = new Vector[allPermuationIndices.size()];
for (int i = 0; i < perms.length; i++) {
int[] permutationIndices = allPermuationIndices.get(i);
int[] vectorValue = new int[permutationIndices.length];
for (int j = 0; j < permutationIndices.length; j++)
vectorValue[j] = vector.apply(permutationIndices[j] + 1);
perms[i] = new Vector(vectorValue);
}
return new Matrix(perms);
}
private static void permutation(int[] prefix, int[] remaining, List<int[]> returnValue) {
if (remaining.length == 0)
returnValue.add(prefix);
else {
for (int i = 0; i < remaining.length; i++) {
int elem = remaining[i];
int[] newPrefix = Arrays.copyOf(prefix, prefix.length + 1);
newPrefix[prefix.length] = elem;
int[] newRemaining = new int[remaining.length - 1];
System.arraycopy(remaining, 0, newRemaining, 0, i);
System.arraycopy(remaining, i + 1, newRemaining, i + 1 - 1, remaining.length - (i + 1));
permutation(newPrefix, newRemaining, returnValue);
}
}
}
Don't bother to understand what it is doing. Try writing a clean implementation on your own (or google for a solution).
Now, if we want to reassign our x, we run into trouble: The type does not match: We declared x to be of type Vector, but perm is returning a Matrix. There are multiple ways to solve this:
We could declare Vector to be a Matrix, i.e., change the signature to Vector extends Matrix. This solution may make sense, but be careful not to break behavioral subtyping: If a class B is a class A, then B must have the same behavior as A and can define additional behavior. Look up the Liskov Substitution Principle on the same note.
We could declare x to be of a supertype of both, Vector and Matrix. Currently, this is Object, but we could also define a new common supertype. This solution may however lose our static type safety. For example, if we want to use x as argument to perm, we need to dynamically cast it to a Vector
We could define a second variable x2 of type Matrix which holds the result. I suggest this solution in this case.
Next, we assign i = 0; and c=1;, which in Java translates to
int i = 0;
int c = 1;
Now, the for-loops:
for m = 1:1:5040
...
end
translates to
for (int m = 1; m <= 5040; i++) {
...
}
The only thing remaining, besides putting it all together, is the if-statement:
if(x2(c,n) == (x2(c,(n+1))-1))
...
end
translates to
if (x2.apply(c, n) == (x2.apply(c, n+1) - 1)) {
...
}
where apply is the method we defined on Matrix. Note that in Java, == will give you strange results if applied to non-primitive types, i.e., everything besides int, byte, char, double, boolean, and float. Generally, you test equivalence using the method equals which is defined on Object.
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]);
}
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());
I have a multidimentional array, as:
private static ArrayList [] [] pVTable = new ArrayList [35] [12];
My first try to initialize it was:
for (ArrayList[] x : pVTable) {
for (ArrayList y : x) {
y = new ArrayList<TableValue>();
}
}
which didn't work.
I ended up doing it more manually, as in:
for ( int i = 0; i < pVTable.length; i++) {
for ( int j = 0; j < pVTable[0].length; j++) {
pVTable [i] [j] = new ArrayList<TableValue>();
}
}
which works fine.
Although I have a solution, I was wondering why the first (more elegant) piece of code doesn't do the same job?
In the first snippet, if we strip away the syntactic sugar of the foreach operator (:), the code translates to:
for (int xIndex = 0; xIndex < pVTable.length; xIndex++) {
ArrayList[] x = pVTable[xIndex];
for (int yIndex = 0; yIndex < x.length; yIndex++) {
ArrayList y = x[yIndex];
y = new ArrayList<TableValue>();
}
}
As you can see, nothing is ever assigned to the actual array – only to the temporary y variable.
In the first example your code although modifies y does not change x.
You are mixing ArrayList (part of collections api) with Arrays, which is rather confusing (for me anyway)
I would suggest something like this instead :
List<Point> myShape = new ArrayList<Point>;
Where point contains two ints representing X and Y.
The scope of the first is incorrect. y is just a placeholder variable. Changing that doesn't change the underlying object, just the object that y refers to. You can see the same problem in the following code snippet:
public static int x = 2;
public static void foo(int y) {
y = 3;//does nothing outside of foo
}
public static void main(String[] args) {
System.out.println(x);//prints 2
foo(x);
System.out.println(x);//prints 2, x hasn't changed.
}