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


i'm making deck , card class game, , have encountered error in creating , using string array. code looks this: error 4 lines bottom says string undealt = ... undealt[0] , says "array required, java.lang.string found" , 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 = 1; <= 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 = currentcard; < deck.size(); i++)     {         int g = - currentcard;         undealt[g] = deck.get(i).tostring();     } } 

the problem having derives these lines in code:

private string[] undealt = new string[52];     :     :     public string tostring() {         string undealt = "undealt cards:\n" + undealt[0] + undealt[1] ...;             :             :     } 

as can see, have defined variable undealt in two different scopes. first declaration @ instance level, have declared undealt instance field of type string[]. scope of instance variable entire class in defined, i.e. instance variable can accessed methods in class.

the second declaration @ local block level, have declared undealt local variable of type string. scope of local variable limited block in declared (blocks delimited curly braces).

as can see, undealt in scope twice in method tostring(), once instance field, second time local variable. compiler has rules uses resolve variable names when conflict in way, , use local variable definition. called "hiding" instance field, i.e. local variable hides instance field.

when compiler tries compile...

        string undealt = "undealt cards:\n" + undealt[0] + undealt[1] ...; 

it determines string[] undealt hidden, , resolve undealt type string.

therefore, when attempt use array element access operator (the brackets after variable name), compiler gives error. has determined undealt local string , therefore not have array elements access.

a practice avoid ever using 2 variables same name in order avoid potential sources of confusion such this. compiler has set of rules use resolve variable accesses in case of conflict, these needn't obvious programmers , can cause confusion.


Comments