gpt4 book ai didi

Java - 变量作用域

转载 作者:行者123 更新时间:2023-12-01 18:37:47 24 4
gpt4 key购买 nike

我是java新手,我有一个 super n00bish问题。 (我确实有一些一般的编程知识)。我试图访问变量“item”但无济于事。有人能找出原因吗?

    public void start() 
{
Scanner input = new Scanner(System.in);

System.out.println("Enter saleman's name: ");
String name = input.next();

int exit = 0;
do
{
System.out.println("Enter item number: ");
String item = input.next();
if (ValidateItem(item) == true)
{
if (Integer.parseInt(item) <=4 && Integer.parseInt(item) >=1)\
{
exit = 1;
}
else
System.out.println("Enter an item number between 1 and 4");
}

if (ValidateItem(item) == false)
{
System.out.println("Enter an item number between 1 and 4");
}

} while (exit == 0);

int exitQuan = 0;
do
{
System.out.println("Enter quantity (1-99): ");
String quant = input.next();
if (ValidateItem(quant) == true)
{
exitQuan = 1;
}
else
System.out.println("Enter a quantity between 1 and 99");
}
while (exitQuan == 0);

if (item == 1)
{
pay = 239.99;
}

最后一个 IF 语句是我缺乏范围的地方。谢谢。

最佳答案

变量作用域仅扩展到声明周围的最小大括号对。例如:

//this could be a method body, an if statement, a loop, whatever
{
int x;
} //x passes out of scope here

因此,当您在 do-while 循环内声明 item 时,一旦退出循环,其作用域就会结束。要解决此问题,请在循环上方声明 item,如下所示:

String item = null; //initialize to null to avoid warning about using an un-initialized variable

do {
System.out.println("Enter item number: ");
item = input.next();

//rest of loop...

} while (exit == 0);

这样,item 将一直可用,直到该方法返回。

关于Java - 变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147813/

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