Question

I'm trying to make sure that the variable num is only 5 digits long, but my while and return statements say that num cannot be resolved to a variable. What can be done?

 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;
  }
}
Was it helpful?

Solution

You need to declare num outside of the loop.

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

This is due to variable scoping. It's a bit annoying, but a variable declared in the do portion of a do-while isn't available in the while portion.

OTHER TIPS

In Java, a variable belongs to the scope that it was declared in. A variable declaration looks like:

<type> <variable name>;

Or, in your case int num. You declare num in the do...while() loop, so it belongs to the do...while() loop. If you want to use num in the method getnum then it's best to declare it near the start of the method:

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;
}

This allows you to access num anywhere inside of the method, so you can assing it and then return it when you're done.

The key thing is to make sure you define "num" outside of your "do" loop:

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;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top