Anthony J
Anthony J

Reputation: 581

About Java function calling

Could someone explain to me when I run this code, I don't get the Sysout statement until I enter my first keyboard input?

    import java.util.Scanner;

    public class test1{

            static Scanner scan = new Scanner(System.in);
            static int k = scan.nextInt();

            public static void main(String[] args) {
                setK();
                System.out.println(" K is: " + k);
        }
            public static void setK(){
                System.out.println("Please input K value");
                k = scan.nextInt();
        }
    }

Upvotes: 0

Views: 67

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726619

This line

static int k = scan.nextInt();

runs during class initialization. It blocks and waits for input of an integer.

This code runs before main because it is a static initialization. It must be complete before the first method of the class is called. At that point k has the first value you have entered. After that, main calls setK, prompting for another input.

You can fix this by removing initialization (i.e. the = scan.nextInt(); part) from declaration of k.

Upvotes: 1

Blablalux
Blablalux

Reputation: 505

Maybe the behaviour you expect would be as follows:

package test;

import java.util.Scanner;

public class ScannerTest {

    static Scanner scan = new Scanner(System.in);
    static int k;

    public static void main(String[] args) {
        System.out.println("Please input K value");
        k = scan.nextInt();
        System.out.println(" K is: " + k);
    }
}

BTW, you should stick to Java naming conventions.

Upvotes: 0

Eran
Eran

Reputation: 393851

The static variables of your test1 class are initialized before your main method is executed. This happens when the class is initialized.

Therefore the

static int k = scan.nextInt();

statement is executed before your main method and waits for input. Only after the input is entered, main starts running and calls setK();, which prints "Please input K value".

I'm not sure this was intentional, since your setK() method seems to be the method that should read the input and assign it to k. Therefore, change your code to :

import java.util.Scanner;

public class test1{

        static Scanner scan = new Scanner(System.in);
        static int k;

        public static void main(String[] args) {
            setK();
            System.out.println(" K is: " + k);
    }
        public static void setK(){
            System.out.println("Please input K value");
            k = scan.nextInt();
    }
}

Upvotes: 2

Related Questions