Java初学者帮助,无法解析变量

时间:2014-04-23 02:45:39

标签: java variables scope

我正在尝试确保变量num只有5位数,但我的while和return语句说num不能解析为变量。可以做些什么?

 import java.util.*;
    public class program1
{
  public static void main(String[] args)
  {
    int num;
    num = getnum();
    System.out.print(num);
  }
  public static int getnum()
  {
    Scanner console = new Scanner(System.in);
    do
    {
    System.out.println("Enter a number that has only five digits ");
    int num = console.nextInt(); 
    }
    while (num < 10000 || num > 99999);
    return num;
  }
}

3 个答案:

答案 0 :(得分:1)

您需要在循环之外声明num

int num;
do
{
    System.out.println("Enter a number that has only five digits ");
    num = console.nextInt(); 
} while (num < 10000 || num > 99999);

这是由于变量范围。这有点烦人,但在do部分的while部分声明的变量在{{1}}部分中不可用。

答案 1 :(得分:0)

在Java中,变量属于声明它的范围。变量声明如下所示:

<type> <variable name>;

或者,在您的情况下int num。您在num循环中声明do...while(),因此它属于do...while()循环。如果您想在方法num中使用getnum,那么最好在方法的开头附近声明它:

public static int getnum() 
{
    Scanner console = new Scanner(System.in);
    int num;
    do
    {
        System.out.println("Enter a number that has only five digits ");
        num = console.nextInt(); 
    }
    while (num < 10000 || num > 99999);
    return num;
}

这使您可以在方法内的任何位置访问num,这样您就可以协助它,然后在完成后将其返回。

答案 2 :(得分:0)

关键是要确保在“do”循环中定义

import java.util.*;

  public class program1 {

    public static void main(String[] args) {
      int num = getnum();
      System.out.print(num);
    }

    public static int getnum() {
      Scanner console = new Scanner(System.in);
      int num;
      do {
        System.out.println("Enter a number that has only five digits ");
        num = console.nextInt(); 
      } while (num < 10000 || num > 99999);
      return num;
   }
}