我是一个完整的 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);
}