Dynamic array of an object - arrays

Maybe the solution is very simple. It must be, but maybe I am overlooking something
I have:
public class Object {
public int pos_x;
public int pos_y;
}
Object testObject[] = new object[10]
and then somewhere in a function
testObject[1].pos_x = 1;
It force closes my app.. how? and why? What can be the cause of this.
Furthermore. Ideally I would need something like this
testObject[].add_new_object();
testobject[].remove_item(3);
can this be done?
Thank you for helping

You have allocated an array that can hold 10 objects.
You also need to allocate the objects.

I'm not sure about the language you are using - if C# you cannot use 'Object' as the class name.
First creating a custom object (the 'object' data type):
public class MyObject {
public int pos_x;
public int pos_y;
}
...fair enough, a very basic class that holds coordinates. Next you want to create an array of MyObject. To do that, you declare your array type as MyObject[] and provide an optional size:
MyObject[] myObjArray = new MyObject[10]; // this gives a zero-based array of 10 elements, from 0-9
Now, you have the task of filling the array. The most common method would be to use a counter variable that counts from 0 to 9, the same elements we have in our array:
for (int i=0; i<=9; i++)
{
myObjArray[i] = new MyObject();
// you can also assign the variables' values here
myObjArray[i].pos_x = GetNextXVal(); // get the X value from somewhere
myObjArray[i].pos_y = GetNextYVal(); // get the y value from somewhere
}
Depending on your language, I'm sure we can point you to some good tutorials, books, or other references to help you get started.
Happy coding!

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
}

Processing string to array

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.

Java help - illegal start to expression/class expected

public class Ship
{
public static int[] size = {3, 2, 3, 5, 4};
public static String[] shipNames = {"Destroyer", "Cruiser", "Submarine",
"Aircraft Carrier", "Battleship"};
public Ship(String shipNames[], int size[])
{
this.shipNames[] = shipNames[];
this.size[] = size[];
}
}
Okay so basically what I'm trying to do is make it so my constructor repeats two static variables...
In another class, I'm calling this object Ship...
newShip = new Ship(Ship.shipNames[i],Ship.size[i]);
But when it sends I get these error messages:
Error: illegal start of expression
Error: '.class' expected
Error: illegal start of expression
Error: '.class' expected
Working with arrays is quite confusing for a beginner such as myself. :(
There are many things wrong here.
When you write something like String shipNames[], the [] is not part of the variable name. It is part of the variable type. So when you are just using the variable, you are not supposed to write them.
You declared the constructor to accept arrays, but you are trying to pass single values to it. Which do you actually want to happen?
When you refer to this.shipNames, presumably you mean to set some field of the object you're constructing. But you have not defined such a field. You already have a thing named shipNames in the class, but it's static - it's part of the class, not the instances.
You have several problems with your code.
First is that your are passing the constructor a string and an int, not an array of strings or array of ints here:
newShip = new Ship(Ship.shipNames[i],Ship.size[i]);
Secondly, you need to receive a string and an int in the constructor, as follows:
public String shipName;
public int size;
public Ship(String shipName, int size)
{
this.shipName = shipName;
this.size = size;
}
There might be other syntax and semantic errors too, but those seem to be the most obvious ones to me.

Updating an Array that belongs to one class from another class

I'm wrote this code a long time ago and thought I understood it at that time but now I'm trying to wrap my head around how it works...
// Main.as
package {
public class Main {
public function Main() {
var fruit:Array = [];
UpdateClass.update(fruit);
trace(fruit); // Traces out the string pushed into it? How??? I think the data would've got lost...
}
}
}
// UpdateClass.as
package {
public class UpdateClass {
public static function update(array:Array):void {
array.push("haha, this is not a fruit!");
}
}
}
I just don't understand how the UpdateClass manages to update Main's fruit array? I'm thinking the data would get lost because it is not returning the new array?... When I try this with Strings and Numbers the data does get lost like expected.
I don't know what I was on when I wrote this but I would like to try and understand the logic behind this.
Thank you.
String and Number are "primitive" data types in AS3, while Array and other objects like MovieClip are "complex" or "reference" data types.
When you pass a primitive, its value is copied, so modifying that doesn't affect the original. When you pass a complex object, it's actually a reference to the object's address in memory, so your function is modifying the original object.
I'm assuming something like following when you say that the value was lost with String and Number:
// UpdateClass.as
package {
public class UpdateClass {
public static function update(num:Number):void {
num = 1;
}
}
}
The reason it was lost was because you got a reference to the original object as num. But the function update changed that reference to another Number object which contained the value '1'. This would be true for array too, if you assign another array to the passed reference like:
// UpdateClass.as
package {
public class UpdateClass {
public static function update(array:Array):void {
array = new Array();
array.push("haha, this is not a fruit!");
}
}
}
But, since you are just calling a method on the passed reference (push), 'array' still refers to the original Array and updates it.

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