Java standard input read

Reading in from System.in — Java [duplicate]

I am not sure how you are supposed to read in from system input from a Java file. I want to be able to call java myProg < file Where file is what I want to be read in as a string and given to myProg in the main method. Any suggestions?

What’s the problem exactly? 1) you don’t know how to start a java program with an argument 2) you don’t know how to open a file within a java program which has the filename as an argument of the main method. or 3) both

Sorry, didn’t see you wanted to read from a file google.co.uk/search?q=java+read+in+from+file+example 754 million hits.

8 Answers 8

You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.

import java.util.Scanner; class MyProg < public static void main(String[] args) < Scanner sc = new Scanner(System.in); System.out.println("Printing the file passed in:"); while(sc.hasNextLine()) System.out.println(sc.nextLine()); >> 

Well, you may read System.in itself as it is a valid InputStream . Or also you can wrap it in a BufferedReader :

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

Wrapping in a BufferedReader seems a bad idea because on Linux (perhaps not in every configuration) it leads to your program not getting the data after you type something in the terminal/PuTTy and press «Enter». In order for the program to get what you’ve typed, you need to send some special character to flush the stream.

In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:

BufferedReader(Reader inputReader) 

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.

To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

InputStreamReader(InputStream inputStream) 

Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

After this statement executes, br is a character-based stream that is linked to the console through System.in.

This is taken from the book Java- The Complete Reference by Herbert Schildt

Источник

How can we read from standard input in Java?

The standard input(stdin) can be represented by System.in in Java. The System.in is an instance of the InputStream class. It means that all its methods work on bytes, not Strings. To read any data from a keyboard, we can use either a Reader class or Scanner class.

Example1

import java.io.*; public class ReadDataFromInput < public static void main (String[] args) < int firstNum, secondNum, result; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try < System.out.println("Enter a first number:"); firstNum = Integer.parseInt(br.readLine()); System.out.println("Enter a second number:"); secondNum = Integer.parseInt(br.readLine()); result = firstNum * secondNum; System.out.println("The Result is: " + result); >catch (IOException ioe) < System.out.println(ioe); >> >

Output

Enter a first number: 15 Enter a second number: 20 The Result is: 300

Example2

import java.util.*; public class ReadDataFromScanner < public static void main (String[] args) < int firstNum, secondNum, result; Scanner scanner = new Scanner(System.in); System.out.println("Enter a first number:"); firstNum = Integer.parseInt(scanner.nextLine()); System.out.println("Enter a second number:"); secondNum = Integer.parseInt(scanner.nextLine()); result = firstNum * secondNum; System.out.println("The Result is: " + result); > >

Output

Enter a first number: 20 Enter a second number: 25 The Result is: 500

Источник

Читайте также:  Php switch case continue

Java how to read standard input in java

println ( «Temperature in Celsius is: » + celsius ) ; > > Conclusion Stdin is used to take the input from the user which is also known as standard input. Using Scanner Class This is probably the most preferred method to take input.

How to Read User Input Through Stdin in Java

The Stdin is used in Java to get input from the user in the form of integers or strings. Java provides a very simplified and easy way to enable users to input values through the keyboard by using a class of java.util.Scanner.

Reading user input in Java through stdin

To use class, an import keyword is used with java.util.Scanne r :

The next step is to create a Scanner object “in”:

Here we are also creating a public class and its syntax is as follows.

In the main function we are required to make the program ready for taking input from the user. The next step is to declare variables for taking input from the user:

The following line asks the user to input two numbers and accepts their values using the in Scanner object. If you want to display something on the screen, then you can do that by using function System.out.println() :

Whereas if you want to take input from the user you can do that by typing:

In the above line, the in.nextInt() reads the integer value from the keyboard that the user enters that will be stored in the variable x . So if you want to input two different integers from the user and want to calculate their sum then you can do that by following the below-mentioned code:

System . out . println ( «Please enter a number: » ) ;
x = in. nextInt ( ) ;
System . out . println ( «Enter another number: » ) ;
y = in. nextInt ( ) ;
int sum = x + y ;
System . out . println ( «Sum of two numbers is: » + sum ) ;

Now the complete code to calculate the sum of two numbers are shown below:

import java.util.Scanner ;
//Creating the main class
public class StdInput <
public static void main ( String [ ] args ) <
//Taking numbers as stdin and adding them
Scanner in = new Scanner ( System . in ) ;
System . out . println ( «Standard Input Example 1 \n ——————» ) ;
int x ;
int y ;
System . out . println ( «Please enter a number: » ) ;
x = in. nextInt ( ) ;
System . out . println ( «Enter another number: » ) ;
y = in. nextInt ( ) ;
int sum = x + y ;
System . out . println ( «Sum of two numbers is: » + sum ) ;
>
>

Note: To run and compile Java code in a Linux terminal you need JDK installed.

You can test the code by creating a java file using any text editor in Linux OS for example:

After that you can compile this file by typing:

After the compiling has been completed, you can run the code by typing:

Similarly in the following example, we are going to input the name as well as the temperature from the user in Fahrenheit. The string data type will be used to make a name as an input from the user and you can do that by typing:

On the other hand, we have used double data type for the temperature as its value can be infractions:

double temp = in. nextDouble ( ) ;
System . out . println ( «Please enter your name: » ) ;
String name = in. next ( ) ;
System . out . println ( «Hi » + name ) ;
System . out . println ( «Please enter temperature in fahrenheit: » ) ;
double temp = in. nextDouble ( ) ;
double celsius = ( temp — 32 ) * 0.55556 ; //(temp-32)*5/9
System . out . println ( «Temperature in Celsius is: » + celsius ) ;

Читайте также:  text-align

So the full code for this example is:

import java.util.Scanner ;
//Creating the main class
public class MProgram <
public static void main ( String [ ] args ) <
//Taking user name and temperature as stdin
Scanner in = new Scanner ( System . in ) ;
System . out . println ( » \n Standard Input Example 2 \n ——————» ) ;
System . out . println ( «Please enter your name: » ) ;
String name = in. next ( ) ;
System . out . println ( «Hi » + name ) ;
System . out . println ( «Please enter temperature in fahrenheit: » ) ;
double temp = in. nextDouble ( ) ;
double celsius = ( temp — 32 ) * 0.55556 ; //(temp-32)*5/9
System . out . println ( «Temperature in Celsius is: » + celsius ) ;
>
>

Conclusion

Stdin is used to take the input from the user which is also known as standard input. In this article we have taught you how you can get the standard input from the user and for this, we have executed two different examples. In the first one we have taken two numbers from the user and then calculated their sum while in the second one, we have taken name and temperature as an input from the user, performed the operation of conversion (Fahrenheit to Celsius), and displayed this information on the screen.

Ways to read input from console in Java, An instance of the Scanner class is created and the ‘nextLine’ function is used to read every line of a string input. An integer value is

Ways to read input from console in Java

In Java, there are four different ways for reading input from the user in the command line environment(console).

1.Using Buffered Reader Class

This is the java classical method to take input, Introduced in JDK1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.

Implementation:

Источник

How to read integer value from the standard input in Java

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?).

I am trying to run it in my eclipse ID with no Syntax error but its not showing anything in the console output when I try to output the read integer values. Why is this so?

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()); 

I would like to comment that under most IDEs System.console will return null when the application is invoked via a launcher making it hard to debug. This seems to be true for IDEA, Eclipse, and NetBeans.

If he enters a string or ‘Enter’ it will throw a NumberFormatException. So it’s better to control the string before parsing it to Integer

Here I am providing 2 examples to read integer value from the standard input

import java.util.Scanner; public class Maxof2 < public static void main(String args[]) < //taking value as command line argument. Scanner in = new Scanner(System.in); System.out.printf("Enter i Value: "); int i = in.nextInt(); System.out.printf("Enter j Value: "); int j = in.nextInt(); if(i >j) System.out.println(i+"i is greater than "+j); else System.out.println(j+" is greater than "+i); > > 
public class ReadandWritewhateveryoutype < public static void main(String args[]) throws java.lang.Exception < System.out.printf("This Program is used to Read and Write what ever you type \nType quit to Exit at any Moment\n\n"); java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in)); String hi; while (!(hi=r.readLine()).startsWith("quit"))System.out.printf("\nYou have typed: %s \n",hi); >> 

I prefer the First Example, it’s easy and quite understandable.
You can compile and run the JAVA programs online at this website: http://ideone.com

Читайте также:  Change use map in javascript

ex 2 might not be the best way to introduce the input stream . or I guess the «System’s Input Objects» to someone new to OOD, Java or coding for that matter — all that descriptive code and you name the key object «r» . a wiseguy, eh? xD +1

public static void main(String[] args) < String input = null; int number = 0; try < BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); input = bufferedReader.readLine(); number = Integer.parseInt(input); >catch (NumberFormatException ex) < System.out.println("Not a number !"); >catch (IOException e) < e.printStackTrace(); >> 

Second answer above is the most simple one.

int n = Integer.parseInt(System.console().readLine()); 

The question is «How to read from standard input».

A console is a device typically associated to the keyboard and display from which a program is launched.

You may wish to test if no Java console device is available, e.g. Java VM not started from a command line or the standard input and output streams are redirected.

Console cons; if ((cons = System.console()) == null)

Using console is a simple way to input numbers. Combined with parseInt()/Double() etc.

s = cons.readLine("Enter a int: "); int i = Integer.parseInt(s); s = cons.readLine("Enter a double: "); double d = Double.parseDouble(s); 

-1 for not answering the question. He doesn’t want to read from a console, but rather from standard input.

Question clearly states that He doesn’t want to read from console. anyway thanks for giving some info on how to read from console.

import java.io.*; public class UserInputInteger < public static void main(String args[])throws IOException < InputStreamReader read = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(read); int number; System.out.println("Enter the number"); number = Integer.parseInt(in.readLine()); >> 

This causes headaches so I updated a solution that will run using the most common hardware and software tools available to users in December 2014. Please note that the JDK/SDK/JRE/Netbeans and their subsequent classes, template libraries compilers, editors and debuggerz are free.

This program was tested with Java v8 u25. It was written and built using
Netbeans IDE 8.0.2, JDK 1.8, OS is win8.1 (apologies) and browser is Chrome (double-apologies) — meant to assist UNIX-cmd-line OG’s deal with modern GUI-Web-based IDEs at ZERO COST — because information (and IDEs) should always be free. By Tapper7. For Everyone.

 package modchk; //Netbeans requirement. import java.util.Scanner; //import java.io.*; is not needed Netbeans automatically includes it. public class Modchk < public static void main(String[] args)< int input1; int input2; //Explicity define the purpose of the .exe to user: System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n" + "Commented and coded for C/C++ programmers new to Java\n"); //create an object that reads integers: Scanner Cin = new Scanner(System.in); //the following will throw() if you don't do you what it tells you or if //int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9 System.out.println("Enter an integer wiseguy: "); input1 = Cin.nextInt(); //this command emulates "cin >> input1;" //I test like Ernie Banks played hardball: "Let's play two!" System.out.println("Enter another integer. anyday now: "); input2 = Cin.nextInt(); //debug the scanner and istream: System.out.println("the 1st N entered by the user was " + input1); System.out.println("the 2nd N entered by the user was " + input2); //"do maths" on vars to make sure they are of use to me: System.out.println("modchk for " + input1); if(2 % input1 == 0)< System.out.print(input1 + " is even\n"); //else< System.out.println(input1 + " is odd"); >//endif input1 //one mo' 'gain (as in istream dbg chk above) System.out.println("modchk for " + input2); if(2 % input2 == 0)< System.out.print(input2 + " is even\n"); >else< System.out.println(input2 + " is odd"); >//endif input2 >//end main >//end Modchk 

Источник

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