Java read int console

Reading standard input via command line java

I am taking a course Algorithms 1 by Sedgwick (Princeton University) and trying to read an integer from standard input which represents the number of integer pairs that will be input , then a list of integer pairs from standard input. For example:

3 //first integer represents number of pairs 12 34 //list of integer pairs 23 56 34 78 
java myProg 3 12 34 23 56 34 78 

at the command prompt in windows command line and read first the 3, then in a loop and process each pair in turn. The code given in the video is this:

package getArgs; public class getInput < public static void main(String[] args) < int N = StdIn.readInt(); //read first integer while (!Stdin.isEmpty())< // loop through pairs int p = StdIn.readInt(); int q = StdIn.readInt(); //process p and q //process each pair >> 
  1. In the code is Stdin.readInt() actual java or pseudocode?
  2. If it is not pseudocode do I need to import a library to access StdIn?
  3. If it is pseudocode do I use a Scanner class to replace StdIn.readInt()?

The rest of the program works , that is the union find class algorithm, this driver to test the program was not explained well and confused me a little.

Читайте также:  Конвертировать тип данных python

Here is my revised attempt — it is ugly

This works but is uglier than the StdIn — can anyone rewrite it using StdIn so that java recognizes StdIn?

Источник

standard console input

Good afternoon I would just like to know the easiest way for standard Console input with java. When it come to int or double input for example in C# it is simple. What would the easiest way be of doing this in java.?

double a; Console.WriteLine("Please enter the value"); a = double.Parse(Console.ReadLine()); Console.WriteLine("thank you for entering " + a); 

5 Answers 5

The direct translation is:

Scanner scan = new Scanner(System.in); System.out.println("Please enter the value"); double i = Double.parse(scan.nextLine()); System.out.println("thank you for entering " + i); 
Scanner scan = new Scanner(System.in); System.out.println("Please enter the value"); double i = scan.nextDouble(); System.out.println("thank you for entering " + i); 
try < InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); DecimalFormat df = new DecimalFormat(); Number n = df.parse(s); double d = n.doubleValue(); >catch (IOException e) < e.printStackTree(); >catch (ParseException e)
 try < InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); double d = Double.parseDouble(s); >catch (IOException e) < e.printStackTree(); >catch (ParseException e)

use java.util.Scanner — it has support to read numbers from STDIN.

JDK 5.0 & above provides a feature to read input from console — Java.util.Scanner. The code below reads a String and an Integer from the console and stores them in the variables.

import java.util.Scanner; public class InputExp < public static void main(String[] args) < String name; int age; Scanner in = new Scanner(System.in);

 // Reads a single line from the console // and stores into name variable name = in.nextLine(); // Reads a integer from the console // and stores into age variable age=in.nextInt(); in.close(); // Prints name and age to the console System.out.println("Name :"+name); System.out.println("Age :"+age); 

Источник

How to get number from console in java?

This is my method that will be called if I want to get a number from user. But if the user also enter a right number just the "else" part will run, why? Can you explain?

 public static int chooseTheTypeOfSorting() < System.out.println("Enter 0 for merge sorting OR enter 1 for bubble sorting"); int numberFromConsole = 0; try < InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); String s = br.readLine(); DecimalFormat df = new DecimalFormat(); Number n = df.parse(s); numberFromConsole = n.intValue(); >catch (ParseException ex) < Logger.getLogger(DoublyLinkedList.class.getName()).log(Level.SEVERE, null, ex); >catch (IOException ex) < Logger.getLogger(DoublyLinkedList.class.getName()).log(Level.SEVERE, null, ex); >return numberFromConsole; > 
 public static void main(String[] args) < int i = 0; i = getRandomNumber(10, 10000); int p = chooseTheTypeOfSorting(); DoublyLinkedList list = new DoublyLinkedList(); for (int j = 0; j < i; j++) < list.add(j, getRandomNumber(10, 10000)); if (p == 0) < //do something. >if (p == 1) < //do something. >else

1 Answer 1

The problem is you're missing an else

 if (p == 0) < //do something. >else if (p == 1) < // you're missing the else here //do something. >else

On reading number from console

Scanner sc = new Scanner(System.in); int num = sc.nextInt(); 

The documentation has more examples.

Note also that you can set the delimiter, and it also has many hasNextXXX methods that you can use to check against InputMismatchException .

See also

Design consideration

You may consider having the helper method filter out "bad" input, so that once you get the type of sorting, it's guaranteed to be valid.

You may also consider using an enum :

See also

Источник

How can I read input from the console using the Scanner class in Java?

Basically, all I want is have the scanner read an input for the username, and assign the input to a String variable.

17 Answers 17

A simple example to illustrate how java.util.Scanner works would be reading a single integer from System.in . It's really quite simple.

Scanner sc = new Scanner(System.in); int i = sc.nextInt(); 

To retrieve a username I would probably use sc.nextLine() .

System.out.println("Enter your username: "); Scanner scanner = new Scanner(System.in); String username = scanner.nextLine(); System.out.println("Your username is " + username); 

You could also use next(String pattern) if you want more control over the input, or just validate the username variable.

You'll find more information on their implementation in the API Documentation for java.util.Scanner

Let's say I only use the scanner once and don't want to clutter my code by initializing an then closing the Scanner - is there a way to get input from the user without constructing a class?

You could use a try with resource statement in JDK 8 such as; try(Scanner scanner = new Scanner(System.in)) < >

Scanner scan = new Scanner(System.in); String myLine = scan.nextLine(); 

Reading Data From The Console

  • BufferedReader is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes. readLine()«just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
  • Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace . «Until the user enters data, the scanning operation may block, waiting for input.«Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream.«A scanner however is not thread safe. It has to be externally synchronized. next() « Finds and returns the next complete token from this scanner. nextInt() « Scans the next token of the input as an int.
String name = null; int number; java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); name = in.readLine(); // If the user has not entered anything, assume the default value. number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it. System.out.println("Name " + name + "\t number " + number); java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s"); name = sc.next(); // It will not leave until the user enters data. number = sc.nextInt(); // We can read specific data. System.out.println("Name " + name + "\t number " + number); // The Console class is not working in the IDE as expected. java.io.Console cnsl = System.console(); if (cnsl != null) < // Read a line from the user input. The cursor blinks after the specified input. name = cnsl.readLine("Name: "); System.out.println("Name entered: " + name); >

Inputs and outputs of Stream

Reader Input: Output: Yash 777 Line1 = Yash 777 7 Line1 = 7 Scanner Input: Output: Yash 777 token1 = Yash token2 = 777 

Источник

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

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 .

Источник

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