Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 Input and Output The console command prompt window provides output to the console and input from the console. In Java this input and output is described by by Objects System.out and System.in respectively. System.in and System.out are objects in and out belonging to the System class; they are System members. Both these objects are examples of text streams called InputStream(in) and PrintStream(out). We have previously encountered several examples of console output. This section will address Input from the console as well as using graphical dialog boxes to perform input/output. 1.1 Console output To output data to the console we use the object System.out along with its methods print() or println(). System.out.println("Hello"); 1.1.1 class String This particular println receives an argument of type String. Concatenating Strings requires some care System.out.println( 3 + 6 + "Hello"); Whats printed? "36Hello" or "9Hello" ? The printout reads "9Hello" because the expression is evaluated from left to right. The first operation is (int)+(int):int The expression (int)+(String) promotes the (int) argument to its text equivalent. The same is true for the other simple types. System.out.println("Hello" + 3 + 6); What is the result? Try this by including the statement in main(…){ ... Was the result what you expected? 1.2 Console input Console input makes use of the object System.in. This object reads single characters and is a quite cumbersome way to extract data from the keyboard. To read a particular type of values, like integers and strings, there is a helper class Scanner provided. To read data from the console keyboard you would use: Scanner keyb = new Scanner( System.in ); This is the first time we've had a reason to create an object. The expression new Scanner( System.in ) creates an object of type Scanner using System.in as a starting value. Scanner is a class that provides methods to read values, ints, doubles, Strings etc, from the source we have specified (System.in). We now have an instance of type Scanner named keyb. Terminology: Constructor. new Scanner invokes the construction of a Scanner instance. A constructor creates an object. This object is referred to by keyb. Example: import java.util.*; class KeyboardReading { public static void main(String [] arg) { Scanner keyb = new Scanner(System.in); System.out.println("Hur many silver dollar coins do you have?"); int nDollars; nDollars = keyb.nextInt(); System.out.println("So you have "+ antalDollar + " coins."); } } Be careful to always include the prompt text before each input statement. Without the promt a user has no idea he is supposed to enter the input, and the program will halt for no apparent reason. 1.2.1 Classes and objects We use (instantiate) the class Scanner to create the object keyb. After the object is created we refer to the object each time we need the services of a scanner, by using the member selector operator . (dot). An object consists of methods and attributes, a common name for these are members. As a rule of thumb, after the creation of the object, we use its attributes by its methods. The attributes themselves are hidden from us. One can imagine what kinds of operations our scanner must apply to System.in to provide us with these services. Behind the scenes: tgb.nextInt() => read each numbersymbol input until a space is reached. Transform these numbers (digit characters) into an int value. Return the int to the caller. Consider the output statement System.out.println(), here we are using two member selectors. System.(dot) and out.(dot). From this we can draw the conclusion that out is a member of System and println() is a member of out. Execution of the example might look as: How many silver dollar coins do you have? 7 So you have 7 coins. 1.2.2 Packages The first statement in the previous example is import java.util.*; All classes within Java are hierarchically organized into packages. A package is a container for classes (among else) that all have a related purpose. If you need to use any class outside of the most basic ones, like System and String, you need to import that package. The Scanner class is contained in a package called java.util, the statement import java.util.*; imports all classes from that package. Note the similarity to a file-system wildcard. We can also write import java.util.Scanner; to specify that its the Scanner class that were using from java.util. 1.2.3 Example problem Assignment: To calculate the area and circumference of a rectangle. An important aspect when you are designing your program from a description like this is to create a model of how the program is supposed to behave. A simple approach for a model is to create a sample dialogue with the executing application. Like State the width of the rectangle: 4 State the height of the rectangle: 2.5 The area is 10.0, the circumference is 13.0 From this dialogue it is fairly straightforward to tell the order of the statements that are required in the program. -prepare for input, print question prompt, do input, print question prompt, do input -do calculations, print answers. import java.util.*; class KeyboardReading { public static void main(String [] arg) { double width, height; Scanner keyb = new Scanner(System.in); System.out.println("State the width of the rectangle:"); width = keyb.nextDouble(); System.out.println("State the height of the rectangle:"); height = keyb.nextDouble(); double circumference = 2*width + 2*height; double area = width* height; System.out.println("The area is "+area+ ", the circumference is "+circumference); } } 1.2.4 Exercise: Write a program that input your age, and with that input calculates the number of days wou have lived. Divide the program in to manageable steps. Consider the dialogue like before. Consider the arithmetic involved. 2 More on operators 2.1 Evaluation rules Consider the statement circumference = 2*width + 2*height; If the width is 4 and the height is 2.5 we would like the calculation to perform as 1: 2*4 =8 2: 2*2.5 =5 Then 3: (1:+2: ) 8 + 5 = 13 Then 4: circumference = 13 To accomplish this, there are two parameters that decide the order of evaluation. 1- Operator priority 2- Direction of evaluation The operator * has the highest priority of the operators involved, hence the two * operations are evaluated first. The * operator evaluates from left to right. Then in order of priority the + operation is evaluated, and lastly the = operator. This gives us exactly the desired order of evaluation as stated above. All operators besides assignment operators are associated left to right. Assignments are associated from right to left. The reason for this is that the following statement int i, j; i = j = 5; Is intuitively read as 1: j = 5, the result of this operation is j, i.e. the value (int) 5. Recall (int)=(int):int 2: i = j, or rather i= 5. The statement will now assign the value 5 to both j, and i (in that order). This is not possible if the left to right association would apply. 2.2 Examples Compound statements require practice to interpret correctly; and certainly to write them. However, if a calculation becomes too complex, don’t hesitate to divide the problem into smaller statements. double circumference = 2*width + 2*height; // can be written as double circumference = 2*( width + height ); // radius of a circle int diameter = 3; // a radius should never be declared as an int double radius = (double)diameter / 2; // (double) transforms diameter into //a double and is an unwelcome tweak in our program. double area = radius*radius* 3.14; // x squared is written as x*x // surface area of a cylinder double radius = 2.0; double height = 4.0; double surfaceArea= 2*radius*radius*3.14159 + height*radius*2*3.14159; // Is preferably divided into double radius = 2.0; double height = 4.0; double sideSurface = height* radius*2*3.14159; double endSurface = radius*radius*3.14159; double surfaceArea = sideSurface + 2*endSurface; The important thing to stress is clarity. Clarity is one of the most important aspects when writing code. Pi is preferably expressed as Math.PI. Operator Precedence postfix operators expr++ expr-- unary operators ++expr --expr +expr -expr ~ ! multiplicative * / % additive + - shift << >> >>> relational < > <= >= instanceof equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || conditional ? : assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= Source: java.sun.com 3 There's more than one way to skin a cat The use of the console for input and output are very useful in many situations but it's not very appealing to the eye. There is a lot of help to make eye-pleasing application in the Java graphical user interface API, swing. To achieve simple input and output operations similar to the console input output we can use the class JOptionPane (almost all classes belonging to swing will start with a J for some reason). JOptionPane provides several methods for creating Message boxes and Input dialogs. If we recall our first input output example import java.util.*; class KeyboardReading { public static void main(String [] arg) { Scanner keyb = new Scanner(System.in); System.out.println("Hur many silver dollar coins do you have?"); int nDollars; nDollars = keyb.nextInt(); System.out.println("So you have "+ antalDollar + " coins."); } } By using JOptionPane this can be translated to, using dialog boxes, import javax.swing.*; class KeyboardReading { public static void main(String [] arg) { String input = JOptionPane.showInputDialog("How many dollars do you have?"); double dollarAmount; dollarAmount = Double.parseDouble( input ); JOptionPane.showMessageDialog( null, "So you have $"+ dollarAmount ); } } The line breaks on line 17 and 13 are for readability. JOptionPane is contained in the swing main package javax.swing. So we are required to import javax.swing.JOptionPane; Input is achieved by using one of JOptionPanes methods showInputPane. These methods return a text, later we need to convert this text into a suitable numeric. Double is a class created for dealing with operations dealing with double values; amongst which we have the method parseDouble(string). The method parseDouble() returns a double value. All of the simple types in Java have a corresponding helper / wrapper class. The term wrapper will be apparent later on. double-Double, int-Integer, byte-Byte, char-Character etc. To present the result to the user we need to display another dialog box; this time with just a message ( no input) JOptionPane.showMessageDialog( null, String s); The expression null is a way to express "no object". showMessageDialog expects us to provide a parent application window as an argument. Since we don’t have an application window, we cannot provide one. This is sometimes an effective strategy when asked for arguments, sometimes not; this is well documented in each class. The String s is of course the displayed message.