答案 0 :(得分:1)
Answer - technically, yes you can.
However, your example is reading a number and throwing it away. The local variable in the static
block goes away at the end of the block.
In general, it is a bad idea to read user input that way because:
static
block is not possible. In your example, if the Scanner
fails to read an integer an unchecked exception will be thrown. That will crash your application with an ExceptionInInitializerError
... static
block will be runNormal practice is to read input in code called (directly or indirectly) from the main(String[])
method. That way you can control when it is read, and catch any exceptions using a handler on the "main" thread.