if you are using the Java SE6 or higher then you can make use of Console clas
Console console = System.console();
if (console==null){
System.out.print("console not available ");
}else {
String line = console.readLine("Enter name :");
System.out.print("your name :"+line);
}
Answer from ajduke on Stack Overflowif you are using the Java SE6 or higher then you can make use of Console clas
Console console = System.console();
if (console==null){
System.out.print("console not available ");
}else {
String line = console.readLine("Enter name :");
System.out.print("your name :"+line);
}
You can do it simply by the following steps:
Use the
BufferedReaderClass and wrap it with theInputStreamReaderClass.BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) //string str = br.readLine(); //for string input int i = Integer.parseInt(br.readLine()); // for Integer InputNow since the
readLinemethod throws anIOExceptionyou need to catch it. The whole code will look like this:try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) //string str = br.readLine(); //for string input int i = Integer.parseInt(br.readLine()); // for Integer Input } catch(IOException ioe) { ioe.PrintStackTrace(); }
java - how to take Char/arithmetic operator as input from user without using Scanner - Stack Overflow
How get user input without using import.util.Scanner in java
parsing - taking integer input in java - Stack Overflow
How do I get user input without using a scanner
java.util.Scanner is the best choice for this task.
From the documentation:
For example, this code allows a user to read a number from System.in:
Scanner sc = new Scanner(System.in); int i = sc.nextInt();
Two lines are all that you need to read an int. Do not underestimate how powerful Scanner is, though. For example, the following code will keep prompting for a number until one is given:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
while (!sc.hasNextInt()) {
System.out.println("A number, please?");
sc.next(); // discard next token, which isn't a valid int
}
int num = sc.nextInt();
System.out.println("Thank you! I received " + num);
That's all you have to write, and thanks to hasNextInt() you won't have to worry about any Integer.parseInt and NumberFormatException at all.
See also
- Java Tutorials/Essential Classes/Basic I/O/Scanning and Formatting
Related questions
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
- How to use Scanner to accept only valid int as input
Other examples
A Scanner can use as its source, among other things, a java.io.File, or a plain String.
Here's an example of using Scanner to tokenize a String and parse into numbers all at once:
Scanner sc = new Scanner("1,2,3,4").useDelimiter(",");
int sum = 0;
while (sc.hasNextInt()) {
sum += sc.nextInt();
}
System.out.println("Sum is " + sum); // prints "Sum is 10"
Here's a slightly more advanced use, using regular expressions:
Scanner sc = new Scanner("OhMyGoodnessHowAreYou?").useDelimiter("(?=[A-Z])");
while (sc.hasNext()) {
System.out.println(sc.next());
} // prints "Oh", "My", "Goodness", "How", "Are", "You?"
As you can see, Scanner is quite powerful! You should prefer it to StringTokenizer, which is now a legacy class.
See also
- Java Tutorials/Essential Classes/Regular expressions
- regular-expressions.info/Tutorial
Related questions
- Scanner vs. StringTokenizer vs. String.Split
Here's my entry, complete with fairly robust error handling and resource management:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Simple demonstration of a reader
*
* @author jasonmp85
*
*/
public class ReaderClass {
/**
* Reads two integers from standard in and prints their sum
*
* @param args
* unused
*/
public static void main(String[] args) {
// System.in is standard in. It's an InputStream, which means
// the methods on it all deal with reading bytes. We want
// to read characters, so we'll wrap it in an
// InputStreamReader, which can read characters into a buffer
InputStreamReader isReader = new InputStreamReader(System.in);
// but even that's not good enough. BufferedReader will
// buffer the input so we can read line-by-line, freeing
// us from manually getting each character and having
// to deal with things like backspace, etc.
// It wraps our InputStreamReader
BufferedReader reader = new BufferedReader(isReader);
try {
System.out.println("Please enter a number:");
int firstInt = readInt(reader);
System.out.println("Please enter a second number:");
int secondInt = readInt(reader);
// printf uses a format string to print values
System.out.printf("%d + %d = %d",
firstInt, secondInt, firstInt + secondInt);
} catch (IOException ioe) {
// IOException is thrown if a reader error occurs
System.err.println("An error occurred reading from the reader, "
+ ioe);
// exit with a non-zero status to signal failure
System.exit(-1);
} finally {
try {
// the finally block gives us a place to ensure that
// we clean up all our resources, namely our reader
reader.close();
} catch (IOException ioe) {
// but even that might throw an error
System.err.println("An error occurred closing the reader, "
+ ioe);
System.exit(-1);
}
}
}
private static int readInt(BufferedReader reader) throws IOException {
while (true) {
try {
// Integer.parseInt turns a string into an int
return Integer.parseInt(reader.readLine());
} catch (NumberFormatException nfe) {
// but it throws an exception if the String doesn't look
// like any integer it recognizes
System.out.println("That's not a number! Try again.");
}
}
}
}
I’ve been trying to get the users input with the ways that my teacher has taught us but they’re not working
Heres the way he taught us
String text = input.nextLine
My program keeps telling me that there’s something wrong with input but I don’t know how to fix it without using a scanner
I'm brushing up on my Java programming by going through the free Java course through the University of Finland. In the course, they teach that the only way to read a user define integer is to do the following:
int value = Integer.valueOf(scanner.nextLine());
But, back when I was in college, we were taught that using the following was okay as well:
int value = scanner.nextInt();
Which one is actually correct or are they both right?
You can use java.util.Scanner (API):
import java.util.Scanner;
//...
Scanner in = new Scanner(System.in);
int num = in.nextInt();
It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).
If you are using Java 6, you can use the following oneliner to read an integer from console:
int n = Integer.parseInt(System.console().readLine());