954,536 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to pass non-static variable to main method

How is it to pass "int [] rank" to main method?

public class Card
{
private int [] rank= new int [13];
private String [] suit={"Spades","Hearts","Diamonds","Clubs"};
private static void rankMaker (int []rank)
{
for (int i=1;i<=13;i++)
rank[i]=i;
}
public static void main (String []args)
{
System.out.println("Jack ="+rank[11]);
}
}

Ignoring the way I am making this deck, what I want to know is how generally can I use "int [] rank" (or any other variable declared outside the main) in other methods?

JavaDeveloper
Newbie Poster
1 post since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

You can't, period.

The normal way is to have the main method do nothing except handle commandline arguments, create a single instance of the application (usually its own class), and start that instance.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Just in case, here's kindof what he's talking about:

public class Card
{
	private int [] rank= new int [13];
	private String [] suit={"Spades","Hearts","Diamonds","Clubs"}; //Not used?


	public Card()
	{
		super();
	}
	


	public void setRanks(int []rank)
	{
		for (int i=1;i<=13;i++)
		{
			rank[i]=i;
		}
	}


	public int getRankAt(int index)
	{
		return this.rank[index];
	}
}


class TestCard
{
	public static void main(String[] args)
	{
		<strong>Card c = new Card();
		System.out.println(c.getRankAt(11) + "");</strong>
	}
}
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You