So I have an arraylist full of floats which currently prints on one line: -221.5, -301.6, 19.2, -249.3, -312.2, 19.7,..
etc
String arrayString = arr.toString();
arrayString= arrayString.substring(1,arrayString.length()-1); //Removes brackets
outputFile.println("array[]={"+arrayString+"};");
How do I format the arraylist so that it prints a new line every three numbers like:
-221.5, -301.6, 19.2,
-249.3, -312.2, 19.7,
...
etc
Try using this...
public static void main(String[] args) {
List<Float> floatList=new ArrayList<Float>();
int i=0;
floatList.add(-221.5f);
floatList.add(-221.6f);
floatList.add(-221.7f);
floatList.add(-221.8f);
floatList.add(-221.9f);
floatList.add(-221.1f);
for (Float float1 : floatList) {
i++;
System.out.print(" "+float1+",");
if(i%3==0){
System.out.println();
}
}
Output:
-221.5, -221.6, -221.7,
-221.8, -221.9, -221.1,
Is a group of three numbers some meaningful quantity or entity in your application (they look like some kind of coordinate to me!)? If so just combine them into an object.
List<MyVector> list = new ArrayList<MyVector>;
list.add(new MyVector(-221.5, -301.6, 19.2));
list.add(new MyVector(-249.3, -312.2, 19.7));
for(MyVector v : list) {
System.out.println(v.toString());
}
Otherwise use @x4rf41's suggestion.
for(int i=0;i<arr.length;i++) {
outputFile.print(arr[i]+" ");
if(i%3==2) {
outputFile.println();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.