Processing string to array - arrays

I want to read four cyclic measured sensors from an arduino and want to display the values with Processing.
My problem is, I get the error message: "Cannot find a class or type named 'Array' " in my processing code when I want to convert my data string into an array.
Does anybody know how to fix it?
import processing.serial.*;
Serial myPort;
String Messdaten;
String MessdatenSplit;
void setup () {
size(500, 500);
println(Serial.list());
myPort = new Serial(this, Serial.list()[0], 9600);
}
void draw(){
}
void serialEvent(Serial myPort){
if (myPort.available() > 0){
String Messdaten = myPort.readStringUntil(3000);
if (Messdaten != null){
trim(Messdaten);
String MessdatenSplit[] = split(Messdaten,",");
MessdatenSplit = new Array[1400];
Natrium = new String[350];
Kalium = new Array[350];
Lithium = new Array[350];
Kupfer = new Array[350];
for (n=0; n<350; n++){
Natrium[n] = 1+4*n;
}
for (k=1; k<350; k++){
Kalium[k] = 1+4*k;
}
for (u=2; u<350; u++){
Kupfer[u] = 1+4*u;
}
for (l=3; l<350; l++){
Lithium[l] = 1+4*l;
}
}
}
}

There is no class named Array (well, there is, but it's not the one you want). That's not how you declare an array.
You declare an array variable by using the type of array you want, then using square brackets []. For example, you're declaring this variable:
String MessdatenSplit;
This declares the MessdatenSplit variable as String, not an array of Strings. Instead, you probably want this:
String[] MessdatenSplit;
Then when you initialize the MessdatenSplit variable, you should again use the type of array it is, and you should also use the square brackets and put the length of the array inside those square brackets. Here you're doing it correctly:
Natrium = new String[350];
(Although, you're missing a declaration for this variable, so you need to add that in for this to really work.)
The above line creates a String array with 350 indexes. But in this next line, and in a few other places, you're initializing it incorrectly:
MessdatenSplit = new Array[1400];
There is no Array keyword. You need to use the type of array it is, like this:
MessdatenSplit = new String[1400];
Note that you can also do the variable declaration and initialization in a single line:
String[] MessdatenSplit = new String[1400];
You might want to start over and declare and initialize a single array variable, then run it to make sure it works. Then add the next array, and run it to see if it works. You're running into trouble because you're trying to write and run your whole sketch at once, when really you need to be testing much smaller steps. Also, you should try to follow standard naming conventions: variables and functions should start with a lower-case letter.

Related

C# - Tuple arrays are mutable, but tuple lists are not. How do I get around this?

I have an array of value pairs I want to modify. I need to add and remove values from this array as well, so I used a list. When I tried to use a list, I encountered an error.
Error CS1612 - Cannot modify the return value of 'List<(int, float)>.this[int]' because it is not a variable
So I decided I would investigate. I tried using an array instead, and it... worked fine? The following code only throws an error on arr1[0].Item1 += 1;.
static void Main()
{
List<(int, float)> arr1 = new List<(int, float)>() { (0, 0) };
(int, float)[] arr2 = new (int, float)[1];
arr1[0].Item1 += 1; // This line
arr2[0].Item1 += 1;
}
Why are tuple arrays mutable, but lists are not? Is this because arrays are simple blocks of data you can modify easily, but lists have a lot of backend behind them that complicates things? Is there a simple way to get around this, or am I going to have to make my own custom class?
Why are tuple arrays mutable, but lists are not?
The list itself is mutable, but not in the way you're doing it. Note that this isn't anything specific to tuples - it's just the case for any mutable struct.
The list indexer getter returns a value (i.e. a copy of the tuple in your case) - so modifying that value wouldn't modify the copy in the list. The compiler is trying to avoid you making a change to a value that's about to be thrown away. Array access doesn't do that - arr2[0] refers to the variable within the array. (An array is effectively a collection of variables.)
If you want to mutate the list, you can have to fetch the tuple, mutate it, then put it back:
var tuple = arr1[0];
tuple.Item1++;
arr1[0] = tuple;
Note that this also explains why you can't use list access expressions as arguments for ref parameters, but you can do the equivalent for arrays:
public void Method(ref int x) => x++;
public void CallMethod()
{
var list = new List<int> { 0 };
var array = new int[] { 0 };
Method(ref list[0]); // Error
Method(ref array[0]); // Valid
}

Multidimensional array of Objects in Kotlin

I'm new in Kotlin, and I want to create a multi dimensional array of a custom class, with null permitted. Something like that
private var array_map = arrayOf<Array<Obstacle?>>()
...
array_map[1][2] = Obstacle()
How can I do it? Thank you!
In case you need the index of each element in the constructor of the elements of the array:
Declaration:
var matrix: Array<Array<Obstacle?>>
Instantiation and initialization:
matrix = Array(numRows) { row ->
Array(numCols) { col ->
Obstacle(row, col)
}
}
You can use private var arrayMap: Array<Array<Obstacle?>> = arrayOf(). Just wrap with as much Array<> as you need.
Not sure if this is what you want, but imagine that Obstacle is a custom class with a field num as below
data class Obstacle(var num: Int){}
A 2D array of the Obstacle object would be as below:
val array: Array<Obstacle?> = arrayOf(Obstacle(123), Obstacle(234))
val arrayOfArray: Array<Array<Obstacle?>> = arrayOf(array)
println(arrayOfArray[0][0]) // would print Obstacle(num=123)
println(arrayOfArray[0][1]) // would print Obstacle(num=234)
So you should be declaring your 2D array as below
val arrayOfArray: Array<Array<Obstacle?>> = arrayOf()
Your code will compile as is. The problem is just that array size can't be changed and arrayOf<Array<Obstacle?>>() creates an empty array, so array_map[1][2] = Obstacle() fails at runtime. (Unless you do array_map = ... somewhere between them. Note that you should prefer val arrayMap, which can't be reassigned, unless you have a specific reason to use var.)
If you want your array to start with nulls, there is arrayOfNulls in the standard library, but it only creates a single-dimensional array, and what you really need is an array of arrays of nulls. You can write a helper function:
inline fun <reified T> matrixOfNulls(n: Int, m: Int) = Array(n) { arrayOfNulls<T>(m) }
private val arrayMap = matrixOfNulls<Obstacle>(5, 5) // example arguments
The approach I always use for this case is:
arr2D = Array(sizeA) { Array(sizeB) { content } }
Note I replaced the sizes by fields names to illustrate that each number/field represents the width and height length of each dimension of the 2D array.
Also, content should be replaced by the main content you want to fill in each coordinate, in your case seems you aims to setup with Obstacle() instances. If you want fill this content in other moment put null or a quick Any() reference.
In this last case, after creating that you can simply perform to set the itens:
arr2D[1][2] = Obstacle()

List.forEach unable to modify element?

I'm attempting to create a list of lists to imitate the functionality of a 2D array in Dart, and I was having trouble for a while figuring out how to make it work.
I originally used List.forEach in order to create the lists and fill them, but after each loop, it's as if I never created the lists. Here's what that code looked like:
currentMap = new List<List<int>>(height);
currentMap.forEach((e) {
e = new List<int>(width);
e.forEach((f) {
f = 1;
});
});
Printing currentMap resulted in a list of null. Here's what I have now:
currentMap = new List<List<int>>(height);
for(int i = 0; i < height; i++) {
currentMap[i] = new List<int>(width);
for(int j = 0; j < width; j++) {
currentMap[i][j] = 1;
}
}
This works exactly as I expected it to.
I understand that this is probably a very basic issue, and I am assuming that forEach does not allow you to modify the element, but I wanted some confirmation on that, and the Dart API docs do not specify except with the phrase "apples the function f to each element..." which may just not be clear to me.
Also, I am aware of things like the List.filled() constructor -- this is just how I am starting to build towards other functionality.
EDIT: Okay, I think I understand now. Arguments are "pass-by-sharing" which means that a copy of a reference to the object is made. This means that you can modify a member of a mutable object that is pointed to by the argument (as follows):
void function(MyObject o) {
o.x = 5;
}
but trying to change what o points to will not change the argument after exiting the function, such as this:
void function(MyObject o) {
MyObject p = new MyObject();
o = p;
}
Dart does not have variable references, all elements are passed as a reference to an object, not to a variable. (In other words, Dart is purely "call-by-sharing" like both Java and JavaScript).
That means that the e parameter to the forEach callback is just a normal local variable, and assigning to it has no effect outside the callback. The same goes for iterators: they return the value in the iterable, but it has no reference back to the iterable after that.
The double loop is what you want when you do "read-modify-write". You read a value from the list, modify it and store it back into the list using the list's index-set operator.
I know you know about List.filled, but just for other readers, I'll give the one-liner to create the two-dimensional array initialized to 1 values:
currentMap = new List.generate(height, (_) => new List.filled(width, 1));
This is because e is only a reference to the List in currentMap not to a currentMap item.
You update a copy of the reference to a List, but this reference has no connection to currentMap.
After the loop, e just gets garbage collected.
This is because of how an Enumerator works and I believe because the Enumerator is immutable You can't modify the collection items when it's being processed in a foreach... removing members and such.
See also:
http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx
What is the best way to modify a list in a 'foreach' loop?

How to create an array that has a set size but unset values?

How do I create an array, which has a set size, that is not known at compile time, but has unset values?
Essentially I want something like int immutable([length]);. length is not known at compile time. Obviously that doesn't compile though.
It'd have to be user-defined. The built-in arrays in D are either static, needed to be known at compile time, or slices into a dynamic array, which can be resized.
Built-in options:
int length = 100;
int[] int_array = new int[length]; // works, contents will be initialized to zero
That's the same as:
int[] int_array;
int_array.length = length;
You can also do immutable(int)[] if you want that, though then you won't be able to set the contents... the normal way to do this would be to write a pure function that creates and sets contents in a mutable array, then returns it:
pure int[] make_array(int length) {
int[] array;
array.length = length;
foreach(i, ref item; array)
item = i; // initialize it to a simple count
return array;
}
// usage:
immutable(int)[] arr = make_array(100); // works
immutable(int[]) iarr = make_array(100); // also works
Mutable data returned from a pure function is the exception to the general prohibition of implicit casting to imuutable: since it comes from a pure function, the compiler knows it is a unique reference, and safe to treat as immutable upon request.
The difference between the first and second line of usage is the first one can be reassigned: arr = something_else[]; /* cool */ whereas the second one cannot be changed at all. No length change, no contents change, no reassignment.
Static arrays are an option, but the length needs to be known at compile time:
int[100] int_array = void; // works, contents uninitialized, non-resizable, but length must be known at compile time
One possible strategy there is to declare a big int_array_buffer, then set int_array = int_array_buffer[0 .. length]. Though, still, int_array will be resizable itself.
To get everything you want, it'll have to be a user-defined type. Something alone these lines could work:
struct MyArray(T) {
#disable this(); // disallow default construction; force a length
// this constructor takes a runtime length and allocates the backing
this(size_t length) { backing = new T[length]; }
private T[] backing = void; // actually holds the data, uninitialized
T[] opSlice() { return backing; } // allow easy conversion to a slice
alias opSlice this; // implicit conversion to slice
}
When passing it to a function, you can pass MyArray!int, or a plain int[]. Thanks to the alias this, it will implicitly convert to int[], and thanks to the D slicing rules, even if the slice is resized in that function, it won't affect your MyArray instance.
Let's look at some usage:
void main() {
int length = 100; // runtime
// MyArray!int uninitialized; // compile error thanks to #disable this
MyArray!int uninitialized = void; // ok, explicitly uninitialized
uninitialized = MyArray!int(length); // created
// or
auto my_array = MyArray!int(length); // also creates it
// my_array.length = 20; // compile error "my_array.opSlice().length is not an lvalue" - it is not resizable
// my_array ~= 1; // compile again, "cannot append type int to type MyArray!int" - again because it is not resizable
int[] slice = my_array; // works, makes passing it to functions that expect normal arrays easy
}
That should give you everything you need. With wrapper structs in D, you can selectively enable and disable functionality of the underlying type with no loss in efficiency.
No need for a wrapper (unless I misunderstood). Just use the allocation primitives in http://dlang.org/phobos/core_memory.html. You can get a chunk of memory that's essentially an uninitialized array of anything you wish.

Converting an int array list to an int array

EDIT:
I am trying to add elements read from a txt document line by line into an array list then convert that array list into an array. Although I am getting errors with my code. It doesnt like the int[] a = lines.toArray(new int[lines.size()]);.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
List<Integer> lines = new ArrayList<Integer>();
File file = new File("10_Random.txt");
try {
Scanner sc = new Scanner(file);
//int line = null;
while (sc.hasNextLine()) {
int i = sc.nextInt();
lines.add(i);
//System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
int[] a = lines.toArray(new int[lines.size()]);
}
}
Edit2: Thanks chaitanya10! all fixed.
int line= null; is wrong,
"null is a special literal that can be of any object reference type".you cant assign null to primitive variables in java like (int, byte, float...). null can only be assigned to objects . remember thatnullis the default vale forobjects` when you don't initialize them.
if you wanna access int as an object use Integer.
Integer line= null;//nowthis would compile
and to convert an list onto array do this.
List.toArray(T[] t) method returns an Object.
do like below.
Integer[] array = lines.toArray(new Integer[lines.size()])
and also your List accepts int[] array and you are tryig to add an int into the list .
change your List declaration like this
List<Integer> lines = new ArrayLis<Integer>();
To print the elements in the array you have to iterate over it
for(int i=0; i<a.length;i++){
system.out.println(a[i])
}
you seem to be a beginner in java. strongly recommend you tohereread about java basic
Two main problems.
You can't assign null to an int. null is a pointer value, and ints in Java are always handled by value, not by reference. Objects can be null, primitive values like int and double can't.
The type declaration of your ArrayList is wrong. The way you're assigning it, each element of the list is expected to be an array of ints. I don't think that's really what you want - the each element is just one int value, so that the list as a whole is analogous to an array.
The second bullet is the reason behind your second and third errors, which I think you'd probably see if you read the error messages all the way through (it's a TypeMismatch error, right?). With your list parameterized to int[], the add method is expecting everything that's added to be of the type int[]. But line is only an int. Similarly, the toArray() method returns an array of whatever type the list is parameterized with. Since you have a list of arrays, toArray() will return an array of arrays. Its return type in this case is int[][], which can't be assigned to int[] a because the type doesn't match.
This should get your code to compile, but it doesn't get into the other issues of validation and whatnot that you have to worry about any time you have input... but for now I'm just going to assume that you've already vetted the input file.
You can use IntStream:
int[] arr = {15, 13, 7, 4, 1, 10, 0, 7, 7, 12, 15};
List<Integer> arrayList = IntStream.of(arr).boxed().collect(Collectors.toList());
System.out.println(arrayList);

Resources