4

i want to read the data from the user in the static block and need to check some condition there but when i am trying to call nextInt() it causes some error

public class Test {
    static int B,H;
    static{
        Scanner s=new Scanner(System.in);
        B=H=0;
        B=s.nextInt();
        H=s.nextInt();
        s.close();
    }
}

Exception in thread "main" java.lang.ExceptionInInitializerError

Caused by: java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at Solution.initialise(Solution.java:21) at Solution.(Solution.java:15)

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Promod Kumar
  • 121
  • 1
  • 8

3 Answers3

1
public class App {
    static int B, H;
    static {
        Scanner s = new Scanner(System.in);
        B = H = 0;
        B = s.nextInt();
        H = s.nextInt();
        s.close();
    }

    public static void main(String[] args) {

    }
}
  • 4
    Although this code might solve the problem, a good answer should explain **what** the code does and **how** it helps – BDL Jul 01 '20 at 12:11
0

From Java7, it is not possible to compile a program without main method. Before that, we can compile the program without the main method but cannot run the program. Just in case if you are trying any version before Java7, try adding System.exit(0) after s.close() (this will stop the compiler from searching for main methods).

0

Try Compiling This

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Demo {
    static int B,H;
    static boolean flag=false;
    static {
        Scanner s=new Scanner(System.in);
        B=s.nextInt();
        H=s.nextInt();
        s.close();
        if (B<=0 || H<=0)
            System.out.println("java.lang.Exception: Breadth and height must be positive");
        else
            flag=true;
    }
public static void main(String[] args){
        if (flag) {
            int area = B*H;
            System.out.print(area);
        }
    }
}
Michael Piefel
  • 18,660
  • 9
  • 81
  • 112