Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Java - Integer input Java - Integer input [ Basic input | Standard input and the io package | Exceptions |Command line usage | Reading from a file ] Basic input It might be thought that a program that reads in two user entered integers and prints out their sum would be a simple piece of code with little of real interest. This assumption is wrong, once the programmer wishes to ensure that errors are detected and also wants to handle the user input channel in a reasonably general fashion. Java provides all these facilities. Unfortunately for those who like simple "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 class Addup { static public void main(String args[]) { InputStreamReader stdin = new InputStreamReader(System.in); BufferedReader console = new BufferedReader(stdin); int num1 = 0, num2 = 0; String str1, str2; try { System.out.print("Enter first number "); str1 = console.readLine(); num1 = Integer.parseInt(str1); System.out.print("Enter second number "); str2 = console.readLine(); num2 = Integer.parseInt(str2); } catch(IOException e) { System.out.println("Input error"); System.exit(1); } catch(NumberFormatException e) { System.out.println(e.getMessage() + " is not numeric"); System.exit(1); } System.out.println(num1 + " + " + num2 + " = " + (num1+num2)); } } Here's a sample dialogue: C:\>java Addup Enter first number 23 Enter second number 78 23 + 78 = 101 C:\> Standard input and the io package The program uses various classes (such as BufferedReader and InputStreamReader) that are defined in the java.io package. It is thus necessary to import this package. import java.io.*; To make the whole program work, it is necessary to read the character stream from the standard input channel, save it as a sequence of characters and then 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 commonly associated with the console device keyboard although operating systems such as Unix allow the user to redirect standard input to almost any data source such as a file, a data communication channel or the output of another program without any need to modify the program in any way. This is a very powerful and useful facility. In order to convert from external numeric format to internal format, Java uses the parseInt() method of the Integer class. The method requires a standard Java string as parameter. The Integer class is sometimes called a wrapper class. It contains various methods etc., associated with the use and manipulation of the primitive data type 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 name, e.g. Integer.parseInt(). Before the conversion can be performed, the input character sequence has to be obtained and stored as 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 detect and remove the terminating return character and construct a properly formed string. The sequence of events is: String str1; int num1; str1 = console.readLine(); num1 = Integer.parseInt(str1); The readLine() method belongs to the class BufferedReader. A BufferedReader object must be associated with an InputStreamReader which in turn must be associated with an InputStream object. This is all handled by the code: InputStreamReader stdin = new InputStreamReader(System.in); BufferedReader console = new BufferedReader(stdin); stdin and console are just local variable names. The definition of the System class includes the line public static final java.io.InputStream in; which establishes the nature of System.in. Exceptions One of the important characteristics of any program designed to be used by humans is that they are likely to make mistakes entering data into the program. In Java, errors are called exceptions. The professional programmer must attempt to detect or catch exceptions caused by user input errors. The Java try/catch mechanism is a very good way of doing this. Unlike some forms of exception handling, it does not make code difficult to read by intermixing error handling code with the main functional code. The main functional code is enclosed in a try block; the statements may throw an exception object which will be caught by a catch block that contains the code to handle the error. Specific types of errors can be handled by specific catch blocks in a manner similar to that shown in the program listed above. The actual types of exception are described in the class definitions. In this simple program, there are two likely exceptions. These are IOException and NumberFormatException. The types of condition that cause these exceptions are obvious from the names. An exception is actually an object that may have 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 case of the NumberFormatException this is simply the string that caused the problem. Here are some specimen dialogues showing input errors and the resulting exceptions. The first example shows the effect of a non-numeric input C:\>java Addup Enter first 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 first number -44 Enter second number +66 For input string: "+66" is not numeric C:\> This is less than ideal behaviour by the parseInt() method. The exit() method of the System class returns from the Java program to the host operating system. The parameter is available to the host operating system as a return code. A common convention is to use the value 0 to indicate that the program has worked properly and any non-zero value to indicate that some sort of error has occurred. Alternative forms of the program It is not necessary to make separate declarations of all the objects and variables. In many cases the value returned by one method can used as a parameter of another method simply by nesting the calls. Using this approach, the code for the current example could be rewritten as shown below. import java.io.*; public class Addup { static public void main(String args[]) { BufferedReader console = new BufferedReader( new InputStreamReader(System.in)); int num1 = 0, num2 = 0; try { System.out.print("Enter first 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"); System.exit(1); } catch(NumberFormatException e) { System.out.println(e.getMessage() + " is not numeric"); System.exit(1); } System.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 find programs that interactively prompt the user for values to be rather tedious. It would be nice if you could type something like this: Addup 22 44 And if you could do that, it would be quite nice to be able to do things such as Addup 34 567 21 11 It is possible to provide input to Java programs this way. 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 yet another carry over from the C programming language). It is the responsibility of the host operating system to grab the characters from the command line and make them available to the program. args is an array of strings. Each member has to be separately converted to an internal integer. Here's the code: public class CmdAdd { static public void main(String args[]) { int total = 0; try { for(int i=0; ijava 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 accessible due to incorrect access rights: C:\>java FileAdd data.txt Couldn't open data.txt (Permission denied) Finally, here is a version of the program that will work past errors in the input file. Errors are, of course, reported but rather than give up at that stage, the program carries on summing any valid data values. Two significant changes have been made to the program. The first is the try/catch associated with numeric format errors is now within the processing loop since any caught error associated with a try/catch results in program flow going to the statement after the try/catch. The second change is slightly more subtle, the error messages are now written using System.err.println() rather than System.out.println() . This enables the host operating system to capture the errors in a different place to the result of the summing operations. Here's the code: import java.io.*; public class FileAdd2 { static public void main(String args[]) { int total = 0; try { BufferedReader in = new BufferedReader(new FileReader(args[0])); String line; while((line = in.readLine()) != null) { try { total += Integer.parseInt(line); } catch(NumberFormatException nfex) { System.err.println(nfex.getMessage() + " is not numeric"); } } in.close(); } catch(FileNotFoundException e) { System.err.println("Couldnt open " + e.getMessage()); System.exit(1); } catch(IOException e) { System.err.println("IO error"); System.exit(1); } System.out.println("Sum = " + total); } } To demonstrate the modified program the data file was modified by including a line that contained the text "three". Here's a listing of the modified data file followed by a run of the program. 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 inside the statement to create the BufferedReader object. In this case, the file variable is not 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 channel from console keyboard 2 error output channel to console display (screen) These three channels are encapsulated in the Java objects System.in, System.out and System.err.   This page is part of a set of notes about the Java programming language prepared by Peter Burden for the module CP4044. A disclaimer applies to this page.