array required, but java.lang.String found card game - arrays

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.

Related

"initializer element is not constant" while creating an Init function

Right now I am trying to implement an Init function for Pre-configured staff. However as in the following code when I try to implement certain function I receive an error initializer element is not constant. I have read many questions with same error however I couldn't relate one to my case.
The code is as follows:
#define CURR_CONFIG_X 4
#define CURR_CONFIG_Y 4
#define CURR_CONFIG_Z 4
typedef struct {
bool *tblX;
bool *tblY;
bool *tblZ;
} indicesInUse_t;
typedef struct {
tblPreCfgs_t *tblPreCfgs;
indicesInUse_t *tblEntryIndicesInUse;
} tblMgmt_t;
indicesInUse_t cfgIndicesInUse(indicesInUse_t *currIndicesInUse); //error takes place in this line
static indicesInUse_t currTblIndicesInUse = cfgIndicesInUse(&currTblIndicesInUse);
static tblMgmt_t flowTbleMgmt = {
.tblEntryIndicesInUse = &currTblEntryIndicesInUse,
};
indicesInUse_t cfgIndicesInUse(indicesInUse_t *currIndicesInUse) {
for (uint16_t index = 0; index < CURR_CONFIG_X; index++) {
currIndicesInUse->tblX[index] = true;
}
for (uint16_t index = 0; index < CURR_CONFIG_Y; index++) {
currIndicesInUse->tblYindex] = true;
}
for (uint16_t index = 0; index < CURR_CONFIG_Z; index++) {
currIndicesInUse->tblZ[index] = true;
}
return *currIndicesInUse;
}
Here's an instance of where you will get the error:
static indicesInUse_t currTblIndicesInUse = cfgIndicesInUse(&currTblIndicesInUse);
Here currTblIndicesInUse is a static variable, so its initializer must be a constant expression. That means it cannot contain dynamically executed code, such as a function call.
There are two ways this can be solved. One is to change the initializer so that it's a constant expression. The other is to remove the initializer, and instead initialize the variable with an assignment statement (inside a function). You would then call that function to initialize it.
For example, the simplest constant initializer would be something like:
static indicesInUse_t currTblIndicesInUse = {NULL, NULL, NULL};
The NULL values could also be the addresses of static bool variables, or bool arrays.
To initialize it dynamically, you'd simply call a function, passing it the address of the struct. The function would then simply set the fields of the structure, e.g.
s_ptr->tblX = ptr_x;
s_ptr->tblY = ptr_y;
s_ptr->tblZ = ptr_z;
You would need to fill in the specifics yourself, depending on what you want to achieve.
Note that in the original posted code, even if the dynamic initializer were allowed, it still wouldn't work because space is never allocated
for the pointer variables. It might be helpful to read a tutorial on how pointers work.

java annotation can not receive param as const array

first I use annotation to receive some params, String and String[], e.g.
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
#Documented
public #interface RedisCacheAble {
String value() default "";
String[] names() default {};
}
#RedisCacheAble(value="XXOO",names = {"a","b"} )
public OrderDetailPO orderTestAble(String op) {}
then my manager said that the value and names must use const because other place may use this values, so I change my code like that:
public static final String XXOO = "xxoo";
public static final String XOARR = {"orderCode","accountId"};
#RedisCacheAble(value=XXOO, names = XOARR )
public OrderDetailPO orderTestAble(String op) { //
}
unfortunately the eclipse throw a error: XOARR must initial as an Array, so it's seems annotation can not recognized a const array, any one know why?
Because annotation attribute value must be const. But even your array is final, its conent is also changeable. So it's not annotation can't recognize const array, there is no const array.

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.

Dynamic array of an object

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!

Resources