Home > other >  how can i send an int value made by a scanner from one of my methods to another method
how can i send an int value made by a scanner from one of my methods to another method

Time:04-28

how can I send an int value made by a scanner from one of my methods to another method. Also, how can I also send it to my main and then send it to another method

CodePudding user response:

To pass a value, you use parameters:

public static void main()
{
    Scanner scan = new Scanner(System.in);// creates keyboard scanner
    int thisInt = scan.nextInt(); // user types 5
    example(thisInt);             // it is passed 5
}

If the method "example" was passed the number with thisInt

public void example(int value)
{
    System.out.print(value);         // prints that 5
}

It would print the value, thisInt, or 5.

EDIT FOR MORE INFO

The void on that method is the reason nothing is returned. With this VERY VERY BASIC code:

public int example(Scanner scan)
{
    return scan.nextInt()
}

You can return a read number to main like so:

int newNumber = example(new Scanner(System.in));

CodePudding user response:

you can declare it as static parameter value and then you can get it from anywhere
example:
static int value=null; to get
ClassWhereValueIsDeclared.value

  •  Tags:  
  • java
  • Related