私は Java の完全な初心者であり、クラスとメソッド間でオブジェクトを渡す方法を理解するのに苦労しています。ある程度の進歩はありましたが、for ループ内でトランプを作成しようとすると、アプリが失敗します。ループを削除すると正常に動作します。エラーを含むクラスの最初の部分を次に示します。
public class Testing
{
public static void main(String[] args)
{
int Deal = 1;
for(int Hand = 0; Hand < Deal; ++Hand)
{
//instantiate and derive values for Player
Card card1 = new Card();
card1.setSuit(); //assign card 1's suit
card1.setValue(); //asign card 1's value
//instantiate and derive values for Computer
Card card2 = new Card();
card2.setSuit(); //assign card 2's suit
card2.setValue(); //assign card 2's suit
//compare the two cards and make sure they are different
cardCompare(card1,card2);
}
//output the two cards to the screen
output(card1,card2);
}
これは私が得るエラーです:
Testing.java:26: error: cannot find symbol
output(card1,card2);
^
symbol: variable card1
location: class Testing
Testing.java:26: error: cannot find symbol
output(card1,card2);
^
symbol: variable card2
location: class Testing
2 errors
for ループを削除するとコードが機能するため、何らかの方法で card1 と card2 という名前がループの外に表示されないと想定していますか? 10 枚か 20 枚のカードを作成したい場合は、それをループで実行したいので、新しいオブジェクトをインスタンス化し、プログラムの他の場所でそれらを使用することについて何かが欠けているに違いありません。
ご協力いただきありがとうございます。
**更新: 最初のフィードバックをありがとう。インスタンス化ステートメントを for ループの外に移動すると、理論的には、ループを使用してそれらのオブジェクトに新しい値を何度も割り当てることができることがわかりました。これだけで、この特定のタスクを完了することができます。
私はまだ興味がありますが、ループ内で新しいオブジェクトをインスタンス化することはできませんが、ループの外でそれらを使用することはできますか? これは何とか可能にならなければならないようです。
public class Testing
{
public static void main(String[] args)
{
int Deal = 1;
//instantiate and derive values for Player
Card card1 = new Card();
//instantiate and derive values for Computer
Card card2 = new Card();
for(int Hand = 0; Hand < Deal; ++Hand)
{
card1.setSuit(); //assign card 1's suit
card1.setValue(); //asign card 1's value
card2.setSuit(); //assign card 2's suit
card2.setValue(); //assign card 2's value
//compare the two cards and make sure they are different
cardCompare(card1,card2);
}
//output the two cards to the screen
output(card1,card2);
}