简体   繁体   中英

Take user input without main method in java

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?

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

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());
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM