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.
Related
I'm making a deck and card class for a game, and have encountered an error in creating and using a string array.
my code looks like this: The error is 4 lines from the bottom where it says String undealt = ... undealt[0] and it says "array required, but java.lang.String found" and now I am confused
import java.util.*;
public class Deck
{
private static int currentCard = 0;
public ArrayList<Card> deck;
private String rank;
private String suit;
private String[] undealt = new String[52];
Deck(String[] ranks, String[] suits, int[] values)
{
for(int i = 1; i <= suits.length; i++)
{
for(int x = 0; x < ranks.length; x++)
{
Card card = new Card(ranks[x], suits[i], values[x]);
deck.add(card);
}
}
shuffle();
}
public String toString()
{
String undealt = "Undealt cards:\n" + undealt[0] + undealt[1] ...;
for(int i = currentCard; i < deck.size(); i++)
{
int g = i - currentCard;
undealt[g] = deck.get(i).toString();
}
}
The problem which you are having derives from these lines in your code:
private String[] undealt = new String[52];
:
:
public String toString() {
String undealt = "Undealt cards:\n" + undealt[0] + undealt[1] ...;
:
:
}
As you can see, you have defined the variable undealt in two different scopes. The first declaration is at the instance level, where you have declared undealt to be an instance field of type String[]. The scope of an instance variable is the entire class in which it is defined, i.e. an instance variable can be accessed by all methods in that class.
The second declaration is at the local block level, where you have declared undealt to be a local variable of type String. The scope of a local variable is limited to the block in which it is declared (blocks are delimited by curly braces).
As you can see, undealt is in scope twice in the method toString(), once as an instance field, the second time as a local variable. The compiler has rules which it uses to resolve variable names when they conflict in this way, and will use the local variable definition. This is called "hiding" the instance field, i.e. the local variable hides the instance field.
When the compiler tries to compile...
String undealt = "Undealt cards:\n" + undealt[0] + undealt[1] ...;
it determines that String[] undealt is hidden, and it will resolve undealt as type String.
Therefore, when you attempt to use the array element access operator (the brackets after the variable name), the compiler gives you an error. It has determined that undealt is a local String and therefore it does not have any array elements to access.
A good practice is to avoid ever using two variables with the same name in order to avoid potential sources of confusion such as this. The compiler has a set of rules to use to resolve variable accesses in the case of a conflict, but these needn't be obvious to programmers and can cause confusion.
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.
I created a simple class with one field. class Test{int value;}
If I use the "preserve references" feature and set it to "all" (i.e. both objects and arrays), then when I simply serialize an array of Test objects, it gets serialized as a JSON object with a special "$values" member with the array values, along with the expected "$id" property to preserve the array reference. That much is fine, but once again the whole thing breaks on deserialization.
Stepping through the source code, I discovered that simply because the test for "IsReadOnlyOrFixedSize" is true, it sets a flag "createdFromNonDefaultConstructor" to true, which doesn't even make any sense, because although it is a fixed size array, it is created from a default constructor, unless it considers any fixed size array constructor a non-default constructor. The bottom line is that it should be able to handle something so basic, and yet it throws this error: "Cannot preserve reference to array or readonly list, or list created from a non-default constructor".
How can I deserialize a basic array while preserving all references in JSON.NET without getting an error?
Got the same issue, I used List<T> instead of T[] to fix it.
You are most likely missing a call to ToObject(...) and a type cast.
This should work:
class Test { public int Value; }
class Program
{
static void Main(string[] args)
{
var array = new Test[2];
var instance = new Test {Value = 123};
array[0] = instance;
array[1] = instance;
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All
};
string serialized = JsonConvert.SerializeObject(array, settings);
// Explicitly call ToObject() and cast to the target type
var deserialized = (Test[]) ((JArray)JsonConvert.DeserializeObject(serialized, settings)).ToObject(typeof(Test[]));
Debug.Assert(deserialized[0].Value == 123);
}
}
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);
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!