gpt4 book ai didi

java - 使用 'for' 循环时出现“找不到符号”错误

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:28 24 4
gpt4 key购买 nike

我是 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);


}

最佳答案

card1 和 card 变量在 for 循环内声明,因此仅在循环内可见。要在循环外使用它,您必须在循环之前声明它。请仔细阅读 Java 作用域规则

关于java - 使用 'for' 循环时出现“找不到符号”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10454345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com