How to Input a String in Java
In the Java programming language beginners quickly encounter one of the limits of Java primitive data types: The basic character variable can store only one letter at a time. This is why Java uses "string" objects to store a sequence, or string, of letters, numbers or symbols. To make a command line, Java stores lines of user input in such a string, you can use the "readLine" method of the handy "Console" object.
Instructions
-
-
1
Click on the first line of your source code file to set the cursor there. Import the code for the "console" class by typing "import java.io.Console;" at the top of your source code.
-
2
Create a new console object by typing the code "Console myConsole = new System.console();"
-
-
3
Write the text you want to use to prompt the user to input his string by typing "String prompt = 'my prompt';" where "my prompt" is the prompt text you wish to use.
-
4
Type the line "String userString = myConsole.readLine(prompt);" to make your program accept a user's string input, and write it to the string object "userString."
-
1
Tips & Warnings
If you want to make your program hide the individual characters your user will be typing in, as in the case of entering passwords, use "readPassword" instead of "readLine." You can also opt to directly set the prompt text, instead of first writing it to a string object, by typing the text in between quotation marks in the parenthesis after "readLine" instead of simply putting in the predefined string object.
References
Resources
- Photo Credit Stockbyte/Stockbyte/Getty Images