Java-可变范围 [英] Java - Variable Scope

查看:53
本文介绍了Java-可变范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,并且有一个超级n00bish问题.(我确实有一些一般的编程知识).我试图访问变量"item"无济于事.有人可以找到原因吗?

I'm brand new to java and I have a super n00bish question. (I do have some general programming knowledge). I'm trying to access the variable "item" to no avail. Can someone spot why?

    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语句是我缺少作用力的地方.谢谢.

The last IF STATEMENT is where I'm lacking scope. Thanks.

推荐答案

变量范围仅扩展到围绕声明的最小括号.例如:

Variable scope only extends to the smallest pair of braces that surround the declaration. For instance:

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

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

Therefore, when you declare item inside of a do-while loop, its scope ends once you exit the loop. To fix this, declare item above the loop like this:

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 才可用.

This way item will be available until the method returns.

这篇关于Java-可变范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆