0

I'm new at programming and currently studying Java. I did a lot of research online and was not able to find my answer. I have to create a code with multiple methods that will return a value.

I know I can call the method by using variable() however doing so will ask the user to enter the value again. I don't want to do that.

I attached a super simple example of what I'm looking to do. Thank you and hope my question was clear.

public class test
{
    public static void welcomeMes(){
        System.out.println("welcome message");
        // does not return anything
    }

    public static int year(){
        int year;
        year = in.nextInt();
        return year;
    }

    public static int month(){
        int month;
        month = in.nextInt();
        return month;
    }

    public static void diplayData(){
       System.out.printf ("month is " + month); // error cannot find symbol
       System.out.printf ("year is " + year); // error cannot find symbol
    }

    public static void main (String [] args){
        welcomeMes();
        year();
        month();
        diplayData();
    }
}
Aniruddha Das
  • 20,520
  • 23
  • 96
  • 132
J S
  • 1
  • 1

3 Answers3

0

The scope of month is local to the function public static int month() but you are trying to use it in public static void diplayData(). You should declare the month variable outside the month function and same with the year variable that the two commented lines up there with error will no longer be there.

user8981117
  • 61
  • 1
  • 7
0

Beacuse your field month and year are availabe only in method what you call. Please add like class field, eg:

public class test{

  private int year =0;
  private int month =0;
    (..)

}

If you want some explanation see eg. this post

newOne
  • 679
  • 2
  • 9
  • 27
0

You can either make them class variables or set them as public.

NickDim
  • 17
  • 3