1

I am converting command line java application to swing GUI. I have a Parser class that reads input from Scanner

Scanner in = new Scanner(System.in);
command = in.nextInt();

Is it possible to pass String instead of (System.in) ? Or, is there a better way to deal?

dev
  • 2,474
  • 7
  • 29
  • 47
  • 1
    Take a look at http://stackoverflow.com/questions/782178/how-do-i-convert-a-string-to-an-inputstream-in-java – BobTheBuilder Nov 17 '13 at 12:36
  • 2
    Or better yet, look at the docs. Short answer is: yes. http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.lang.String%29 – Erik Nedwidek Nov 17 '13 at 12:37

2 Answers2

2

You can use nextLine() of Scanner class to read string value entered in console.

Below is an example:

 public class Parser {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Please enter command:");
    String command = in.nextLine();

    JOptionPane.showMessageDialog(null, command);

}

}

Eneter string value in console:

Please enter command:
Java Command

enter image description here

Mengjun
  • 3,159
  • 1
  • 15
  • 21
1

If you want pass Strings in Scanner just use Java's next() method

Scanner in = new Scanner(System.in);
String command = in.next();

I hope this is what you were looking for.

rawplutonium
  • 386
  • 5
  • 15
BilalDja
  • 1,072
  • 1
  • 9
  • 17