+ 1

What are the different ways of accepting input through the user in Java

6th Aug 2017, 6:48 PM
Akansha Nigam
Akansha Nigam - avatar
2 Réponses
+ 11
You can use any of the following ways based on the requirements. • Scanner class import java.util.Scanner; Scanner scan = new Scanner(System.in); String s = scan.next(); int i = scan.nextInt(); • BufferedReader and InputStreamReader classes import java.io.BufferedReader; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int i = Integer.parseInt(br.readLine()); • DataInputStream class import java.io.DataInputStream; DataInputStream dis = new DataInputStream(System.in); int i = dis.readInt(); • The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader. • Console class import java.io.Console; Console console = System.console(); String s = console.readLine(); int i = Integer.parseInt(console.readLine()); Apparently, this method does not work well in some IDEs.
6th Aug 2017, 6:51 PM
Dev
Dev - avatar
+ 2
Could also use swing. Such as JOptionPane. import javax.swing.JOptionPane; String input = JOptionPane.showInputDialog(null, "User Input"); *Won't work on CodePlayground*
6th Aug 2017, 7:06 PM
Rrestoring faith
Rrestoring faith - avatar