Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format()
for output conversion.
I was wondering if there's an input conversion method akin to C's scanf
in Java?
What Does Scanf Mean? In the C programming language, scanf is a function that reads formatted data from stdin (i.e, the standard input stream, which is usually the keyboard, unless redirected) and then writes the results into the arguments given.
The Scanner class is used to get user input, and it is found in the java.util package.
The scanf() function allows us to read one or multiple values entered by the user through the keyboard at the console. The printf() function is used to print or display one or multiple values in the output to the user at the console.
System.in is an InputStream which is typically connected to keyboard input of console programs. System.in is not used as often since data is commonly passed to a command line Java application via command line arguments, or configuration files. In applications with GUI the input to the application is given via the GUI.
Take a look at this site, it explains two methods for reading from console in java, using Scanner
or the classical InputStreamReader
from System.in.
Following code is taken from cited website:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ReadConsoleSystem { public static void main(String[] args) { System.out.println("Enter something here : "); try{ BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in)); String s = bufferRead.readLine(); System.out.println(s); } catch(IOException e) { e.printStackTrace(); } } }
--
import java.util.Scanner; public class ReadConsoleScanner { public static void main(String[] args) { System.out.println("Enter something here : "); String sWhatever; Scanner scanIn = new Scanner(System.in); sWhatever = scanIn.nextLine(); scanIn.close(); System.out.println(sWhatever); } }
Regards.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With