Table of Contents
ReadLine in Java
How to read a line of user input in Java.
It seems that reading a line of user input is quite difficult in Java. I don’t do much Java, but I had to try it out when someone asked. Indeed, it is much more difficult than needed. I’ll stick to Python. (Update 2008-11-07: it’s not that bad in Java if you use Console.readLine)
$ javac ReadingLine.java $ java ReadingLine Hello, what's your name? Tero Hello Tero!
import java.io.*; class ReadingLine{ public static String readLine() { String s = ""; try { InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); s = in.readLine(); } catch (Exception e) { System.out.println("Error! Exception: "+e); } return s; } public static void main(String[] args) { System.out.print("Hello, what's your name? "); String name=readLine(); System.out.println("Hello "+name+"!"); System.out.println(""); System.out.println("More tutorials in http://www.iki.fi/karvinen"); } }
It's much easier in Python
$ python helloTero.py Hello, what's your name? Tero Hello Tero!
name = raw_input("Hello, what's your name? ") print("Hello "+name+"!") print("") print("More tutorials in http://www.iki.fi/karvinen")
Console.readLine() version in Java
import java.io.Console; public class helloTero { public static void main(String[] args) { Console console = System.console(); String name = console.readLine("Hello, what's your name? "); System.out.println("Hello, " + name + "! Check http://www.iki.fi/karvinen"); } }
$ javac helloTero.java $ java helloTero Hello, what's your name? Tero Hello, Tero! Check http://www.iki.fi/karvinen
Thanks to Juhani for pointing out Console.readLine()!