New to programming, new to java. I seem to understand the basic pieces like classes and their components, methods, etc, but I can't figure out how to put them together. For example, I'm following the tutorials and trying to write a class Card that can become any card based on args passed during construction.
My first problem is, if I declare class Card public (line 5), the compiler says illegal start of expression.
If I remove public, it continues to the println statement, where it complains non-static variable can't be referenced from a static environment. That is because I'm working inside the main method, which is always static, right? So, I need to add methods to Card that will read the internal state and give it to the println statement, would that work?
public class Deck {
public static void main(String[] args) {
class Card {
public int rank;
public int suit;
public Card(int startSuit, int startRank) {
rank = startRank;
suit = startSuit;
}
}
Card aceOfSpades = new Card(1, 1);
System.out.println("Card is ..." + Card.rank + " of " + Card.suit);
}
}
Round Two Here is the new code, the file is Card.java:
public class Card {
//declare states
//rank 1-13 for ace-king
//suit 1-4 spade,heart,club,diamond
public int rank;
public int suit;
//constructor
public Card(int startSuit, int startRank) {
rank = startRank;
suit = startSuit;
}
//methods for Card
public static void main(String[] args) {
//call Card constructor
//make card ace of spades (1,1)
Card aceOfSpades = new Card(1,1);
//read internal state of new Card object
//what kind of card is it?
System.out.println("Card is ..." + rank + " of " + suit);
}
}
I balanced my braces, main method is now part of Card class, I think its looking better. The oney compile errors are now associated with the variables in the println statement. (non-static variable suit can't be referenced from a static context.) I think this means I have to write methods like getSuit() and getRank() that will read the variable states and then use the method in my println and not the variables themselves?
That method would look like this, right?
public int getSuit() {
return suit;
}
(pls bear with me, my formatting isn't coming out exactly correct, I'll work on it)