Java system input integer

How to get the user input in Java?

I attempted to create a calculator, but I can not get it to work because I don’t know how to get user input. How can I get the user input in Java?

Uh, what’s your question? You just posted some code and said you don’t like pointers. Not understanding pointers can still come back to bite you in java if you don’t understand pass by reference and pass by value.

29 Answers 29

One of the simplest ways is to use a Scanner object as follows:

import java.util.Scanner; Scanner reader = new Scanner(System.in); // Reading from System.in System.out.println("Enter a number: "); int n = reader.nextInt(); // Scans the next token of the input as an int. //once finished reader.close(); 

If you close a Scanner object opened to System.in, you will not be able to reopen System.in until the program is finished.

Yeah, ksnortum is right, you get a NoSuchElementException. Somewhat useful related question about why you cannot reopen System.in after closing it.

You can use any of the following options 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; import java.io.InputStreamReader; //. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int i = Integer.parseInt(s); 

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

Читайте также:  Позиционирование css относительно центра

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.

Note that DataInputStream is for reading binary data. Using readInt on System.in does not parse an integer from the character data, it will instead reinterpret the unicode values and return nonsense. See DataInput#readInt for details ( DataInputStream implements DataInput ).

this is great, would love to see the required imports added for completeness. It would also really help those who need it.

This answer would be a lot more helpful if it mentioned what the requirements actually were. I’ve started a bounty to try to fix this.

For completness sake, you could actually just System.in.read() too since System.in is an InputStream anyways, no need to for any of the wrappers x’] Although that’s definitely frowned upon.

You can use the Scanner class or the Console class

Console console = System.console(); String input = console.readLine("Enter input:"); 

I believe this will return an error running from almost any IDE. confirmed that intelliJ is having the same issue.

You can get user input using BufferedReader .

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String accStr; System.out.println("Enter your Account number: "); accStr = br.readLine(); 

It will store a String value in accStr so you have to parse it to an int using Integer.parseInt .

int accInt = Integer.parseInt(accStr); 

Here is how you can get the keyboard inputs:

Scanner scanner = new Scanner (System.in); System.out.print("Enter your name"); String name = scanner.next(); // Get what the user types. 

The best two options are BufferedReader and Scanner .

The most widely used method is Scanner and I personally prefer it because of its simplicity and easy implementation, as well as its powerful utility to parse text into primitive data.

Advantages of Using Scanner

  • Easy to use the Scanner class
  • Easy input of numbers (int, short, byte, float, long and double)
  • Exceptions are unchecked which is more convenient. It is up to the programmer to be civilized, and specify or catch the exceptions.
  • Is able to read lines, white spaces, and regex-delimited tokens

Advantages of BufferedInputStream

  • BufferedInputStream is about reading in blocks of data rather than a single byte at a time
  • Can read chars, char arrays, and lines
  • Throws checked exceptions
  • Fast performance
  • Synchronized (you cannot share Scanner between threads)

Overall each input method has different purposes.

  • If you are inputting large amount of data BufferedReader might be better for you
  • If you are inputting lots of numbers Scanner does automatic parsing which is very convenient

For more basic uses I would recommend the Scanner because it is easier to use and easier to write programs with. Here is a quick example of how to create a Scanner . I will provide a comprehensive example below of how to use the Scanner

Scanner scanner = new Scanner (System.in); // create scanner System.out.print("Enter your name"); // prompt user name = scanner.next(); // get user input 

(For more info about BufferedReader see How to use a BufferedReader and see Reading lines of Chars)

java.util.Scanner

import java.util.InputMismatchException; // import the exception catching class import java.util.Scanner; // import the scanner class public class RunScanner < // main method which will run your program public static void main(String args[]) < // create your new scanner // Note: since scanner is opened to "System.in" closing it will close "System.in". // Do not close scanner until you no longer want to use it at all. Scanner scanner = new Scanner(System.in); // PROMPT THE USER // Note: when using scanner it is recommended to prompt the user with "System.out.print" or "System.out.println" System.out.println("Please enter a number"); // use "try" to catch invalid inputs try < // get integer with "nextInt()" int n = scanner.nextInt(); System.out.println("Please enter a decimal"); // PROMPT // get decimal with "nextFloat()" float f = scanner.nextFloat(); System.out.println("Please enter a word"); // PROMPT // get single word with "next()" String s = scanner.next(); // ---- Note: Scanner.nextInt() does not consume a nextLine character /n // ---- In order to read a new line we first need to clear the current nextLine by reading it: scanner.nextLine(); // ---- System.out.println("Please enter a line"); // PROMPT // get line with "nextLine()" String l = scanner.nextLine(); // do something with the input System.out.println("The number entered was: " + n); System.out.println("The decimal entered was: " + f); System.out.println("The word entered was: " + s); System.out.println("The line entered was: " + l); >catch (InputMismatchException e) < System.out.println("\tInvalid input entered. Please enter the specified input"); >scanner.close(); // close the scanner so it doesn't leak > > 

Note: Other classes such as Console and DataInputStream are also viable alternatives.

Console has some powerful features such as ability to read passwords, however, is not available in all IDE’s (such as Eclipse). The reason this occurs is because Eclipse runs your application as a background process and not as a top-level process with a system console. Here is a link to a useful example on how to implement the Console class.

DataInputStream is primarily used for reading input as a primitive datatype, from an underlying input stream, in a machine-independent way. DataInputStream is usually used for reading binary data. It also provides convenience methods for reading certain data types. For example, it has a method to read a UTF String which can contain any number of lines within them.

However, it is a more complicated class and harder to implement so not recommended for beginners. Here is a link to a useful example how to implement a DataInputStream .

Источник

Java: how to read an input int

This is an example of execution I would like to realize:

Integer: eight Input error - Invalid value for an int. Reinsert: 8 secondtoken Input error - Invalid value for an int. Reinsert: 8 8 + 7 = 15 

And this is the (incorrect) code I tried to implement:

import java.util.Scanner; import java.util.InputMismatchException; class ReadInt < public static void main(String[] args)< Scanner in = new Scanner(System.in); boolean check; int i = 0; System.out.print("Integer: "); do< check = true; try< i = in.nextInt(); >catch (InputMismatchException e) < System.err.println("Input error - Invalid value for an int."); System.out.print("Reinsert: "); check = false; >> while (!check); System.out.print(i + " + 7 mt24 mb12">
    javainputjava.util.scanner
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this question" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="question" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="1" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)">edited Jan 10, 2013 at 13:53
Veger
37.2k11 gold badges105 silver badges116 bronze badges
asked Jan 10, 2013 at 13:52
1
    Can you please elaborate on what you mean by if I don't insert an int, I'm not actually able to solve the exception?
    – Jimmy Thompson
    Jan 10, 2013 at 14:00
Add a comment|

2 Answers 2

Reset to default
1

Use a BufferedReader. Check NumberFormatException. Otherwise very similar to what you have. Like so .

import java.io.*; public class ReadInt < public static void main(String[] args) throws Exception < BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean check; int i = 0; System.out.print("Integer: "); do< check = true; try< i = Integer.parseInt(in.readLine()); >catch (NumberFormatException e) < System.err.println("Input error - Invalid value for an int."); System.out.print("Reinsert: "); check = false; >> while (!check); System.out.print(i + " + 7 mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
answered Jan 10, 2013 at 14:01
0
Add a comment|
1

To use with tokens:

int i = Integer.parseInt(in.next());
int i; while (true) < System.out.print("Enter a number: "); try < i = Integer.parseInt(in.next()); break; >catch (NumberFormatException e) < System.out.println("Not a valid number"); >> //do stuff with i 

That above code works with tokens.

Источник

taking integer input in java

I am actually new to java programming and am finding it difficult to take integer input and storing it in variables. i would like it if someone could tell me how to do it or provide with an example like adding two numbers given by the user..

What have you tried so far? Have you researched the Scanner class (if you're reading from the console)?

4 Answers 4

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."); >> > > 

This is good for learning but as Ash suggested the Scanner class is much more convenient (java.sun.com/javase/6/docs/api/java/util/Scanner.html)

I'm not sure that an object which has a BNF grammar in its Javadoc header is the most user-friendly thing. Sure it's convenient and powerful for parsing console input, but it's stateful and a lot more complex than explaining how to read a single line and parse it as an int.

java.util.Scanner is the best choice for this task.

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

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

Источник

Оцените статью