Home > Back-end >  Take user input without main method in java
Take user input without main method in java

Time:05-05

Basically I am working on Selenium automation in with TestNG, I want to take user input for one field, and to take user input I am taking help of scanner class. But it is not working without main class. Can anyone help me out here?

CodePudding user response:

You can create a static void function and then call it on your created class. Maybe it can help?

CodePudding user response:

One way is to accept input in the static method.

import java.io.BufferedReader;
import java.io.InputStreamReader;

class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!"); 
  }

  static {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int num1 = Integer.parseInt(br.readLine());
        int num2 = Integer.parseInt(br.readLine());
        System.out.println("Sum of two numbers is "   (num1   num2));
    } catch (Exception e) {
        System.out.print(e.toString());
    }
  }
}
  • Related