How to Read a Line of Integers Java
Java - Integer input
Basic input
It might exist thought that a programme that reads in 2 user entered integers and prints out their sum would be a simple piece of lawmaking with little of existent interest. This assumption is wrong, once the programmer wishes to ensure that errors are detected and too wants to handle the user input channel in a reasonably general way. Java provides all these facilities. Unfortunately for those who like uncomplicated "proof-of-concept" programs, the Java programmer has to do it properly - or not at all.
Here's a Java program that prompts the user to enter two integer numbers and prints out their sum:
import java.io.*; public grade Addup { static public void master(String args[]) { InputStreamReader stdin = new InputStreamReader(Organisation.in); BufferedReader panel = new BufferedReader(stdin); int num1 = 0, num2 = 0; String str1, str2; try { System.out.impress("Enter offset number "); str1 = panel.readLine(); num1 = Integer.parseInt(str1); System.out.impress("Enter second number "); str2 = console.readLine(); num2 = Integer.parseInt(str2); } catch(IOException east) { System.out.println("Input error"); System.exit(1); } take hold of(NumberFormatException e) { System.out.println(eastward.getMessage() + " is not numeric"); System.exit(ane); } System.out.println(num1 + " + " + num2 + " = " + (num1+num2)); } }
Here'southward a sample dialogue:
C:\>coffee Addup Enter first number 23 Enter second number 78 23 + 78 = 101 C:\>
Standard input and the io package
The plan uses various classes (such equally BufferedReader and InputStreamReader) that are defined in the coffee.io package. It is thus necessary to import this package.
import java.io.*;
To make the whole program piece of work, it is necessary to read the grapheme stream from the standard input aqueduct, save it equally a sequence of characters and and so use a method that converts the numeric value from the external character format to the internal binary format.
C programmers and Unix users talk about the standard input channel, often abbreviated to stdin. This is unremarkably associated with the console device keyboard although operating systems such equally Unix allow the user to redirect standard input to almost any data source such as a file, a data communication aqueduct or the output of another plan without any demand to modify the program in any manner. This is a very powerful and useful facility.
In lodge to convert from external numeric format to internal format, Java uses the parseInt() method of the Integer grade. The method requires a standard Java cord equally parameter. The Integer class is sometimes called a wrapper class. It contains various methods etc., associated with the use and manipulation of the archaic data blazon int. The Integer class is an example of a static class. This means you can use its' methods without needing to create an object of type Integer first. You use the classname intstead of the object proper name, east.g. Integer.parseInt().
Before the conversion can be performed, the input graphic symbol sequence has to exist obtained and stored every bit a string. A console keyboard user will normally terminate the input by pressing the ENTER key, thus marking out a line of text on console screen. The terminated line of input can be obtained, as a string, using the readLine() input method. This will internally observe and remove the terminating render character and construct a properly formed string. The sequence of events is:
String str1; int num1; str1 = panel.readLine(); num1 = Integer.parseInt(str1);
The readLine() method belongs to the grade BufferedReader. A BufferedReader object must be associated with an InputStreamReader which in plow must be associated with an InputStream object.
This is all handled by the code:
InputStreamReader stdin = new InputStreamReader(Organisation.in); BufferedReader console = new BufferedReader(stdin);
stdin and console are merely local variable names. The definition of the System class includes the line
public static final java.io.InputStream in;
which establishes the nature of Organization.in.
Exceptions
One of the important characteristics of whatever program designed to be used by humans is that they are likely to make mistakes inbound data into the programme. In Java, errors are called exceptions. The professional developer must attempt to detect or catch exceptions acquired by user input errors. The Java try/catch mechanism is a very good style of doing this. Unlike some forms of exception handling, information technology does not brand code hard to read by intermixing error handling code with the master functional code. The principal functional code is enclosed in a try cake; the statements may throw an exception object which will be caught by a catch block that contains the code to handle the fault. Specific types of errors tin be handled past specific catch blocks in a mode similar to that shown in the program listed above.
The bodily types of exception are described in the class definitions. In this simple program, at that place are two probable exceptions. These are IOException and NumberFormatException. The types of condition that crusade these exceptions are obvious from the names. An exception is really an object that may take properties and methods, some of which may provide further information about the exception. The commonest exception method is getMessage() that returns a string that might be informative. In the example of the NumberFormatException this is simply the string that caused the problem.
Hither are some specimen dialogues showing input errors and the resulting exceptions.
The first instance shows the result of a non-numeric input
C:\>java Addup Enter showtime number 23 Enter second number two For input string: "two" is not numeric C:\>
The second example is rather more surprising
C:\>java Addup Enter showtime number -44 Enter 2nd number +66 For input string: "+66" is not numeric C:\>
This is less than platonic behaviour by the parseInt() method.
The exit() method of the System class returns from the Coffee plan to the host operating system. The parameter is available to the host operating organization as a return code. A mutual convention is to use the value 0 to indicate that the program has worked properly and any not-zero value to point that some sort of fault has occurred.
Culling forms of the plan
It is non necessary to make carve up declarations of all the objects and variables. In many cases the value returned by 1 method tin used as a parameter of another method merely past nesting the calls. Using this arroyo, the code for the current example could exist rewritten every bit shown below.
import java.io.*; public class Addup { static public void main(String args[]) { BufferedReader console = new BufferedReader( new InputStreamReader(Arrangement.in)); int num1 = 0, num2 = 0; try { Arrangement.out.impress("Enter offset number "); num1=Integer.parseInt(console.readLine()); System.out.print("Enter second number "); num2=Integer.parseInt(console.readLine()); } catch(IOException e) { System.out.println("Input error"); Organization.exit(one); } catch(NumberFormatException east) { Arrangement.out.println(e.getMessage() + " is not numeric"); System.exit(1); } Arrangement.out.println(num1 + " + " + num2 + " = " + (num1+num2)); } }
It is worthwhile to compare this with the earlier code listing.
Getting values from the command line
Users who are familiar with the use of a command line interface and also with scripting discover programs that interactively prompt the user for values to be rather tedious. It would be overnice if you lot could blazon something like this:
Addup 22 44
And if y'all could practice that, information technology would exist quite dainty to be able to do things such as
Addup 34 567 21 11
Information technology is possible to provide input to Java programs this mode. The strings that appear on the command line are available within the program via the args[] parameter of the function main() which must appear in every executable program. (This name is nevertheless another carry over from the C programming language). It is the responsibleness of the host operating system to grab the characters from the command line and make them available to the program.
args is an assortment of strings. Each member has to exist separately converted to an internal integer. Here's the code:
public form CmdAdd { static public void main(String args[]) { int total = 0; try { for(int i=0; i<args.length; i++) total += Integer.parseInt(args[i]); } take hold of(NumberFormatException e) { Organization.out.println(e.getMessage() + " is non numeric"); System.exit(1); } System.out.println("Sum = " + total); } }
And here'due south a typical dialogue:
C:\>java CmdAdd 12 34 56 78 Sum = 180 C:\>
The basic program pattern is to "loop through" or "walk" the assortment of strings, converting each one to an internal integer and accumulating the result. To do this using whatever standard looping mechanism you need to know how many strings there are to process. This is equivalent to knowing the size (or number of elements) of the array args. Coffee arrays have a standard belongings that gives this value, information technology is called length. A professional programmer would first bank check that the size of the array was non-aught.
Discover that in this instance the programmer has not specifically created the array args. This is washed by the Java interpreter and is a special case associated with the part main().
The for statement is i of four loop statements bachelor in Java. The syntax and flow of control is illustrated below.
for( initialisation_exp; loop_condition; increment_exp ) { // statements }
The parentheses folllowing for comprise three expressions separated by semicolons with the following pregnant:
-
The initialisation expression is evaluated but once at the get-go of the loop. Usually this will declare a loop variable and assign its initial value.
-
The loop status is a boolean expression which is evaluated each time through the loop. If it is false the statements in the body of the for loop are executed once more. If it is true, the loop terminates.
- After the statements in the torso of the loop take been executed, the increase expression is executed. This is usally an assignment argument which volition change the value of the loop variable. In this way, the loop variable is used to count the number of iterations through the loop.
-
The flow of program execution returns to the second step to a higher place.
The program uses the assignment operator (+=) to accumulate the full value. The assignment operator is just a shorthand fashion of writing:
full = total + Integer.parseInt(args[i]);
Reading values from a file
If a program that sums numbers read from the control line is useful, 1 that sums numbers read from a text file would be equally desirable. Here'due south a program that takes a file proper name from the control line, opens the file and sums the numbers read. An assumption is made that the file format is one number per line.
Here'south the code:
import coffee.io.*; public class FileAdd { static public void primary(Cord args[]) { int full = 0; endeavour { FileReader file = new FileReader(args[0]); BufferedReader in = new BufferedReader(file); Cord line; while((line = in.readLine()) != aught) { total += Integer.parseInt(line); } in.shut(); } grab(NumberFormatException e) { System.out.println(e.getMessage() + " is non numeric"); System.exit(1); } take hold of(FileNotFoundException e) { System.out.println("Couldn't open up " + due east.getMessage()); System.exit(ane); } catch(IOException e) { System.out.println("IO error"); Arrangement.exit(1); } System.out.println("sum = " + full); } }
To demonstrate the program, yous will need to create a textfile. Exercise this with a text editor, type the lines of data shown beneath, and save the file every bit data.txt.
23 44 11 22
Here's a listing of the file followed past a run of the program.
C:\>type data.txt 23 44 xi 22 C:\>java FileAdd data.txt sum = 100 C:\>
Much of the code for this program should be familiar from the previous examples. There are ii statements which create and open up the file. These are:
FileReader file = new FileReader(args[0]); BufferedReader in = new BufferedReader(file);
The object file is an example of the FileReader form. (Reader classes are used specfically for reading text files). The file object is used to create an case of the BufferedReader form. This improves efficiency past buffering the file reading process. The in variable is a reference to the BufferedReader object created.
On most operating systems a text file consists of lines. A line is a sequence of characters terminated past an end-of-line grapheme. The BufferedReader class's readLine() method will read characters from the file until the end-of-line graphic symbol is read.
In designing a program of this nature, information technology is important to consider how it stops. Conspicuously it should stop when there is no more than information bachelor. The readLine() method returns the special value nil when information technology has attempted to read across the cease of file. This actually means that it has not returned a string since it has not plant a line to read.
If you are reading from a file, it is obvious that the operating organization will know how big the file is and generate suitable indication when the end of the file is reached. It is not and then obvious what happens if you are reading from the keyboard or a communications aqueduct. In the case of the keyboard, on many operating systems there is a special central (or key combination) that is detected by the operating arrangement. This is typically Ctrl-D on Unix systems, or Ctrl-Z on Windows. For a communications channel, failure or remote closure is detected past the operating arrangement and reported to applications in the aforementioned mode as end of file.
This program uses a while loop rather than a for loop. This is basically because the plan cannot decide in advance how many lines are going to be read in so information technology only repeats the operation while some status is true.
In this example the loop continuation condition is
(line = in.readLine()) != null
This is, of course, a boolean expression but the left hand operand of the != operator repays more than careful examination. In example you're confused by the parentheses etc., this left hand operand is
(line = in.readLine())
This is an assignment expression. A piece of syntax of the grade a = b is an expression and has a value in just the same style equally a + b has a value. The value of the consignment expression is the value of the left paw operand. Strictly you could say that the evaluation of an consignment expression, as a side-issue, results in the storage of a value. Of class you could write this piece of code without taking advantage of the assignment operator. It would look something similar this:
boolean eof = fake; do { line = in.readLine(); if(line == null) eof = true; else total += Integer.parseInt(line); } while(!eof);
This is noticeably more clumsy and the use of assignment expressions in the mode shown in the example is to be encouraged.
You may take noticed the apparent actress gear up of parentheses around the consignment expression. These are necessary since the assignment operator (=) has a lower precedence and then the conditional operator !=. If they were omitted the code would start compare in.readLine() with null and then endeavor to assign the consequence of the comparing to line. (Really the lawmaking wouldn't compile - can you run across why?)
The try/catch blocks should, past now, be familiar and you won't be surprised to know that, if the file doesn't exist, a FileNotFoundException is thrown. This can be caught by the following catch cake:
catch(FileNotFoundException e) { Arrangement.out.println("Couldn't open " + e.getMessage()); System.exit(ane); }
If some other file mistake occurs, an IOException is thrown.
Hither's some examples. First an attempt to read from a non-existent file:
C:\>java FileAdd xyz Couldn't open xyz (The system cannot find the file specified)
And now an example in which the file does exist but is not attainable due to incorrect access rights:
C:\>java FileAdd data.txt Couldn't open up data.txt (Permission denied)
Finally, here is a version of the plan that will work past errors in the input file. Errors are, of course, reported just rather than give up at that stage, the program carries on summing whatsoever valid information values. Two significant changes take been made to the program. The first is the try/catch associated with numeric format errors is now within the processing loop since whatever defenseless mistake associated with a try/grab results in program period going to the statement after the attempt/catch. The 2d change is slightly more than subtle, the error letters are now written using Organisation.err.println() rather than System.out.println() . This enables the host operating system to capture the errors in a different identify to the upshot of the summing operations.
Here's the code:
import java.io.*; public class FileAdd2 { static public void main(String args[]) { int full = 0; try { BufferedReader in = new BufferedReader(new FileReader(args[0])); String line; while((line = in.readLine()) != nix) { try { total += Integer.parseInt(line); } take hold of(NumberFormatException nfex) { System.err.println(nfex.getMessage() + " is non numeric"); } } in.close(); } take hold of(FileNotFoundException eastward) { System.err.println("Couldnt open " + e.getMessage()); System.exit(1); } catch(IOException due east) { Organisation.err.println("IO error"); System.exit(1); } Arrangement.out.println("Sum = " + total); } }
To demonstrate the modified program the data file was modified by including a line that contained the text "three". Hither'southward a listing of the modified data file followed past a run of the programme.
C:\>java FileAdd2 data.txt For input string: "three" is not numeric Sum = 100
Note that another change made in this version of the program is that the statement to create a FileReader object is nested within the argument to create the BufferedReader object. In this example, the file variable is non required.
Each Java program is launched with three "pre-opened" I/O channels that are normally associated with the console. These are:
| 0 | standard output channel | to console display (screen) |
| 1 | standard input aqueduct | from panel keyboard |
| 2 | error output aqueduct | to console display (screen) |
These iii channels are encapsulated in the Java objects Organisation.in, System.out and System.err.
Source: http://www.scit.wlv.ac.uk/~in8297/CP4044/workshops/w03.html
Post a Comment for "How to Read a Line of Integers Java"