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
for Loop Reading files String conversions Random class Fall 2008 ACS-1903 1 for Loop • a specialized form of the while loop … a pre-test loop. • The for loop allows the programmer to initialize a control variable, test a condition, and modify the control variable all in one line of code. • The for loop takes the form: for(initialization; test; update) { loop statements } • Example: Squares.java Fall 2008 ACS-1903 2 The for Loop Flowchart initialization boolean expression? true statement(s) update false Fall 2008 ACS-1903 3 for Loop • The initialization section … initialize its control variable. • The test section of the for statement is similar to the test in a while loop. • The update section of the for loop is the last thing to execute in the loop. • Example: UserSquares.java Fall 2008 ACS-1903 4 The for Loop Initialization • Typically, for loops initialize a counting variable • Can initialize multiple variables. • Variables declared in this section have scope only for the for loop. Fall 2008 ACS-1903 5 The Update Expression • usually used to increment or decrement the counting variable(s) • last section to execute in the loop. • may update multiple variables. • Each variable updated is executed as if it were on a line by itself. Fall 2008 ACS-1903 6 Modifying The Control Variable • bad programming style to update the control variable of a for loop within the body of the loop • leads to hard to maintain code and difficult debugging. • update section should be used to update the control variable. Fall 2008 ACS-1903 7 Multiple Initializations and Updates • The for loop may initialize and update multiple variables. for(int i = 5, int j = 0; i < 10 || j < 20; i++, j+=2){ … loop statements } • only the semicolons are mandatory. for(;;){ … loop statements }//infinite loop. We will not consider using for’s like the above We do not cover the use of the break or continue statements • If left out, the test section defaults to true. Fall 2008 ACS-1903 8 Nested Loops • Like if statements, loops can be nested. • If a loop is nested, the inner loop will execute all of its iterations each time the outer loop executes once. for(int i = 0; i < 10; i++) for(int j = 0; j < 10; j++) { … loop statements } • The loop statements in this example execute 100 times. • Example: Clock.java Fall 2008 ACS-1903 9 The break And continue Statements • a break statement can be used to abnormally terminate a loop. • use of the break statement in loops bypasses the normal mechanisms and makes the code hard to read and maintain. • considered bad form to use the break statement in this manner. Fall 2008 ACS-1903 10 The continue Statement • a continue statement will cause the currently executing iteration of a loop to terminate and the next iteration will begin. • a continue statement will cause the evaluation of the condition in while and for loops. • as with the break statement, the continue statement should be avoided because it makes the code hard to read and debug. Fall 2008 ACS-1903 11 Deciding Which Loops to Use • The while loop: • Pretest loop • Use it where you do not want the statements to execute if the condition is false in the beginning. • The do-while loop: • Post-test loop • Use it where you want the statements to execute at least one time. • The for loop: • Pretest loop • Use it where there is some type of counting variable that can be evaluated. Fall 2008 ACS-1903 12 Files • Input … reading (we’ll focus on reading files first) • Output … writing • Errors can occur • Attempting to read a file that does not exist • Writing to a file that is protected • These types of errors need to be provided for Fall 2008 ACS-1903 13 Exceptions • When something unexpected happens in a Java program, an exception is thrown. • The method currently executing when the exception is thrown must either handle the exception, or, pass it up the line. • Handling the exception is discussed later. • To pass it up the line, the method needs a throws clause in the method header. • For now just accept that this must be done Fall 2008 ACS-1903 14 Exceptions • To insert a throws clause in a method header, simply add the word throws and the name of the expected exception. • The class Exception can be used to catch all exceptions. public static void main(String[] args) throws IOException{…} • File I/O is a checked exception (meaning the exception must be handled or passed up). • A program with file I/O will generate a compile-time error if the exception is not handled or passed up. • Example: FileWriteDemo.java Fall 2008 ACS-1903 15 Reading Data From a File • Java provides several classes to read data from a file. • FileReader • Open an existing file for reading and establish a connection with it. • BufferedReader • Uses a buffer to allow the reading of full lines of text at a time rather than one byte at a time. Fall 2008 ACS-1903 16 Detecting The End of a File • The readLine() method of the BufferedReader class will return null if the end of the file has been reached. FileReader freader = new FileReader(filename); BufferedReader inputFile = new BufferedReader(freader); // Read the first item. String str = inputFile.readLine(); // If an item was read, display it // and read the remaining items. while (str != null) We say end-of-file occurs when we { read a line, but there are no more System.out.println(str); lines left to read. End-of-file is str = inputFile.readLine(); detected by checking for a null line. } inputFile.close();// close the file when done. At this time you need to know that we can read files one line at a time, until end-of-file, and each line is available as a string Fall 2008 ACS-1903 17 String Value Conversion • The readLine() method of the BufferedReader class only reads in text as a String object. • Strings that represent numbers can be converted and stored into primitive variables. • Java provides wrapper classes that make conversion easy. Fall 2008 ACS-1903 18 String Value Conversion Method Description Integer.parseInt(str) This method accepts a string that contains a number and returns the number as an int. Short.parseShort(str) This method accepts a string that contains a number and returns the number as a short. Byte.parseByte(str) This method accepts a string that contains a number and returns the number as a byte. Long.parseLong(str) This method accepts a string that contains a number and returns the number as a long. Float.parseFloat(str) This method accepts a string that contains a number and returns the number as a float. Double.parseDouble(str) This method accepts a string that contains a number and returns the number as a double. Example: FileSum.java Fall 2008 ACS-1903 19 The Random Class • Some applications, such as games and simulations, require the use of randomly generated numbers. • The Java API has a class, Random, for this purpose. To use the Random class, use the import statement and create an instance of the class. import java.util.Random; Random randomNumbers = new Random(); Fall 2008 ACS-1903 20 Some Methods of the Random Class Method Description nextDouble() Returns the next random number as a double. The number will be within the range of 0.0 and 1.0. nextFloat() Returns the next random number as a float. The number will be within the range of 0.0 and 1.0. nextInt() Returns the next random number as an int. The number will be within the range of an int, which is –2,147,483,648 to +2,147,483,648. nextInt(int n) This method accepts an integer argument, n. It returns a random number as an int. The number will be within the range of 0 to n. Example: MathTutor.java Fall 2008 ACS-1903 21 Example Suppose we want to program a game that involves two dice. Die will be a class from which we can instantiate two objects (one for each die). We can toss the pair of dice 1,000,000 times and see what the average throw is. ASIDE: A UML class diagram showing the classes the program has, each of their attributes and methods, and the relationships between classes: 2 DiceGame die1 numberSides die2 generator main() toss() A dicegame is played with two dice Java code: DiceGame.java Fall 2008 1 Die Random nextInt() A die uses a random number generator Die.java ACS-1903 22 ASIDE: a UML sequence diagram showing how the objects interact Die is a class from which we instantiate two objects. We toss the pair of dice 1,000,000 times. System.out DiceGame main() printLn() new() new() die1:Die new() : Random die2:Die new() Loop [1,000,000 times] toss() :Random nextInt() toss() nextInt() printLn() Fall 2008 ACS-1903 23