Download presentation
Presentation is loading. Please wait.
Published byBrenda Montgomery Modified over 8 years ago
1
Chapter 4 Loops and Files
2
2 Contents 1. The Increment and Decrement Operators 2. The while Loop 3. Using the while Loop for Input Validation 4. The do-while Loop 5. The for Loop 6. Running Totals and Sentinel Values 7. Nested Loops 8. The break and continue Statements
3
3 Contents 9. Deciding Which Loop to Use 10. Introduction to File Input and Output 11. The Random Class
4
4 1. The Increment and Decrement Operators Java provides a set of simple unary operators designed just for incrementing and decrementing variables. Incrementing: increasing by one Decrementing: decreasing by one Increment operator ++ Decrement operator --
5
5 1. The Increment and Decrement Operators Incrementing the variable number 1. number = number + 1; 2. number += 1; 3. number++; 4. ++number; Decrementing a variable 1. number = number - 1; 2. number -= 1; 3. number--; 4. --number;
6
6 Postfix and Prefix Modes Postfix mode The operator is placed after the variable. number++; number--; Prefix mode The operator is placed before the variable. ++number; --number;
7
7 Postfix and Prefix Modes
8
8 The Difference between Postfix and Prefix Modes The difference is important if these operators ++ and -- are used in statements that do more than just increment or decrement. Example: number = 4; System.out.println(number++); This statement does two things: Calls println method to display the value of number Increments number But which happens first?
9
9 The Difference between Postfix and Prefix Modes Postfix mode causes the increment to happen after the value of the variable is used in the expression. number = 4; System.out.println(number++); 1. The println method will display 4 and then 2. number will be incremented to 5. number = 4; System.out.println(number); number = number + 1;
10
10 The Difference between Postfix and Prefix Modes The prefix mode causes the increment to happen first. number = 4; System.out.println(++number); number will be incremented to 5 and then The println method will display 5. number = 4; number = number + 1; System.out.println(number);
11
11 The Difference between Postfix and Prefix Modes int x = 1, y; y = x++; // Postfix increment 1.It assigns the value of x to the variable y 2.The variable x is incremented int x = 1, y; y = ++x; // Prefix increment 1.The variable x is incremented 2.It assigns the value of x to the variable y
12
12 2. The while Loop Problem: Write a program to ask a number n, and print “Hello” n times. Get n count <= n count = 1 Print “Hello” Add 1 to count true false
13
13 2. The while Loop
14
14 2. The while Loop while(count <= n) { System.out.println(“Hello”); count++; } Test this boolean expression. If the boolean expression is true, perform these statements. After executing the body of the loop, start over.
15
15 2. The while Loop Logic of a while loop boolea n Expressi on Statement(s) true false
16
16 2. The while Loop while(BooleanExpression) Statement; To repeat a block of statements while(BooleanExpression) { Statement1; Statement2; // Place as many statements here // as necessary } Loop header Body of the loop
17
17 The while Loop Is a Pretest Loop The while loop is known as a pretest loop because it tests its expression before each iteration. int number = 10; while(number <= 5) { System.out.println(“Hello”); number++; } The loop will never iterate if the boolean expression is false to start with.
18
18 Infinite Loops If a loop does not have a way of stopping, it is called an infinite loop. An infinite loop continues to repeat until the program is interrupted. int number = 1; while(number <= 5) { System.out.println(“Hello”); } This is an infinite loop because it does not contain a statement that changes the value of the number variable. Each time the boolean expression is tested, number will contain the value 1.
19
19 Infinite Loops It's also possible to create an infinite loop by accidentally placing a semicolon after the first line of the while loop. int number = 1; while(number <= 5); { System.out.println(“Hello”); number++; } This while loop will forever execute the null statement, which does nothing.
20
20 Don't Forget the Braces with a Block of Statements If you are using a block statement, don't forget to enclose all of the statements in a set of braces. If the braces are accidentally left out, the while statement executes only the very next statement. int number = 1; while(number <= 5) System.out.println(“Hello”); number++; The number++ statement is not in the body of the loop.
21
21 Programming Style and the while Loop Avoid this style of programming while(number <=5 ) { System.out.println(“Hello”); number++; } The programming style If there is only one statement repeated by the loop, it should appear on the line after the while statement and be indented one additional level. If the loop repeats a block, each line inside the braces should be indented.
22
22 3. Using the while Loop for Input Validation The while loop can be used to create input routines that repeat until acceptable data is entered. Input validation is the process of inspecting data given to a program by the user and determining if it is valid. A good program should give clear instructions about the kind of input that is acceptable. Do not assume that the user has followed those instructions.
23
23 3. Using the while Loop for Input Validation The while loop is especially useful for validating input: If an invalid input is entered, a loop can require that the user re-enter it as many times as necessary.
24
24 Input Validation Logic Problem: Write a program to ask for a number in the range of 1 through 100. Is the value invalid? Read the first value Display an error message. Read another value true false
25
25 Input Validation Logic input = JOptionPane.showInputDialog(“Enter a number “ + “ in the range of 1 through 100.”); number = Integer.parseInt(input); // Validate the input while(number 100) { input=JoptionPane.showInputDialog(“Invalid input.“ + “Enter a number in the range of 1 through 100.”); number = Integer.parseInt(input); }
26
26 4. The do-while Loop The do-while loop is a posttest loop, which means its boolean expression is tested after each iteration. The do-while loop's format do Statement; while(BooleanExpression);
27
27 4. The do-while Loop The do-while loop's format do { Statement1; Statement2; // Place as many statements here as necessary }while(BooleanExpression); The do-while loop must be terminated with a semicolon.
28
28 4. The do-while Loop The do-while loop is a posttest loop. The do-while loop always performs at least one iteration, even if the boolean expression is false to begin with. Boolea n expressi on Statement(s) true false You should use the do-while loop when you want to make sure the loop executes at least once.
29
29 4. The do-while Loop Problem: Write a program that averages a series of three test scores for a student. After the average is displayed, it asks the user if he or she wants to average another set of test scores. The program repeats as long as the user enter Y for yes. The programmer had no way of knowing the number of times the loop would iterate. This is because the loop asks the user if he or she wants to repeat the process. This type of loop is known as a user controlled loop because it allows the user to decide the number of iterations.
30
30 4. The do-while Loop Does the user want to average another set ? Get three test scores true false Calculate and print the average test score
31
31 4. The do-while Loop
32
32 4. The do-while Loop
33
33 5. The for Loop In general, there are two categories of loops Conditional loops Executes as long as a particular condition exists. An input validation loop User controlled loop You have no way of knowing the number of times it will iterate. Count-controlled loops Repeats a specific number of times
34
34 5. The for Loop A count controlled loop must process three elements It must initialize a control variable to a starting value. It must test the control variable by comparing it to a maximum value. When the control variable reaches its maximum value, the loop terminates. It must update the control variable during each iteration. This is usually done by incrementing the variable.
35
35 The Format of the for Loop for(Initialization; Test; Update) Statement; for(Initialization; Test; Update) { Statement1; Statement2; // Place as many statements here as necessary } Loop header Loop body
36
36 The Format of the for Loop for(Initialization; Test; Update) { Statement1; Statement2; // Place as many statements here as necessary } ● To initialize a control variable to its starting value ● The first action performed by the loop ● It is only done once. ● A boolean expression that controls the execution of the loop ● As long as this expression is true, the body will repeat. ● The for loop is a pretest loop, so it evaluates the test expression before each iteration. ● It executes at the end of each iteration. ● Typically, this is a statement that increments the loop's control variable.
37
37 Logic of the for Loop Evaluate the test expression Initialization true false Loop bodyUpdate
38
38 Sequence of Events in the for Loop Here is an example of a simple for loop that prints “Hello” five times: int count; for(count = 1; count <= 5; count++) System.out.println(“Hello”);
39
39 Sequence of Events in the for Loop for(count = 1; count <= 5; count++) System.out.println(“Hello”); Step 1: Perform the initialization expression Step 2: Evaluation the test expression. If it is true, go to Step 3. Otherwise, terminate the loop. Step 3: Execute the body of the loop. Step 4: Perform the update expression, then go back to Step 2.
40
40 Logic of the for Loop count <= 5 Assign 1 to count true false println statement Increment count
41
41 The Control Variable During the execution of the loop This variable takes on the values 1 through 5 When the test expression count <= 5 is false, the loop terminates. This variable keeps a count of the number of iterations, it is often called a counter variable. The control variable can be used within the body of the loop.
42
42 The Control Variable Print the numbers 1 through 10: int number; for(number = 1; number <= 10; number++) System.out.print(number + “ “); This loop will produce the following output: 1 2 3 4 5 6 7 8 9 10
43
43 An Example Write a program to display a table showing the numbers 1 to 10 and their squares.
44
44 The for Loop Is a Pretest Loop The for loop tests its boolean expression before it performs an iteration pretest loop The following loop will never iterate int count; for(count = 11; count <= 10; count++) System.out.println(“Hello”); The control variable count is initialized to a value that makes the boolean expression false from the beginning, this loop terminates as soon as it begins.
45
45 Modifying the Control Variable in the Body of the for Loop Be careful not to place a statement that modifies the control variable in the body of the for loop. All modifications of the control variable should take place in the update expression. int x; for(x = 1; x < 10; x++) { System.out.println(x); x++; } The output: 1 3 5 7 9
46
46 Other Forms of the Update Expression Display all the even numbers from 2 through 100 int number; for(number = 2; number <= 100; number += 2) System.out.println(number); Display the numbers from 10 to 0 int number; for(number = 10; number >= 0; number--) System.out.println(number);
47
47 Declaring a Variable in the for Loop's Initialization Expression We can declare and initialize the control variable in the initialization expression of the for loop. int number; for(number = 1; number <= 10; number++) System.out.println(number); for(int number = 1; number <= 10; number++) System.out.println(number);
48
48 Declaring a Variable in the for Loop's Initialization Expression When a variable is declared in the initialization expression of a for loop, the scope of the variable is limited to the loop. We can not access the variable outside the loop. int number; for(number = 1; number <= 5; number++) System.out.println(number); System.out.println(“number is now “ + number); for(int number = 1; number <= 5; number++) System.out.println(number); System.out.println(“number is now “ + number); 1 2 3 4 5 number is now 6 ERROR !
49
49 Creating a User Controlled for Loop Sometimes we want the user to determine the maximum value of the control variable in a for loop. The user determines the number of times the loop iterates. Write a program to display the numbers and their squares. The program allows the user to enter the maximum value to display.
50
50 Creating a User Controlled for Loop number <= maximum value Assign 1 to number true false Display number and its square Increment number Allow the user to enter the maximum value
51
51 Creating a User Controlled for Loop
52
52 Using Multiple Statements in Initialization and Update Expr. It is possible to execute more than one statement in the initialization expression and the update expression. Separate the statements with commas int x, y; for(x = 1, y = 1; x <= 5; x++) { System.out.println(x + “ plus “ + y + “equals “ + (x + y)); } 1 plus 1 equals 2 2 plus 1 equals 3 3 plus 1 equals 4 4 plus 1 equals 5 5 plus 1 equals 6
53
53 Using Multiple Statements in Initialization and Update Expr. int x, y; for(x = 1, y = 1; x <= 5; x++, y++) { System.out.println(x + “ plus “ + y + “equals “ + (x + y)); } 1 plus 1 equals 2 2 plus 2 equals 4 3 plus 3 equals 6 4 plus 4 equals 8 5 plus 5 equals 10
54
54 Checkpoint 4.9 4.10 4.11 4.12
55
55 6. Running Totals and Sentinel Values Problem: Calculate a company's total sales over a period of time by taking daily sales figures as input. Input Number of days Sales of each day Output Total sales We need a variable to accumulate sales of each day.
56
56 Running Totals The total of a series of numbers is sometimes called a running total The numbers are gathered and summed during the running of a loop. A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the running total is called an accumulator
57
57 Running Totals count <= number of days Assign 0 to the accumulator totalSales Assign 1 to the control variable count true false Allow the user to enter the sales figures Add sales to totalSales Increment count Allow the user to enter the number of days
58
58 6. Running Totals and Sentinel Values
59
59 Running Totals An accumulator is a variable It is initialized with a starting value, which is usually 0. It accumulates a sum of numbers by having the numbers added to it.
60
60 Using a Sentinel Value Problem: Write a program to calculate the total points earned by a soccer team has earned over a series of games. The user enters a series of point values, and then -1 to signal the end of the list. Input: The user enters a series of point values, -1 when finished. Output: Total points A special value signals the end of the list. The value -1 was chosen for the special value in this program because it is not possible for a team to score negative points.
61
61 Using a Sentinel Value Number of points != -1 true false Add points to totalPoints Get the next number of points Assign 0 to the accumulator totalPoints Get the first number of points
62
62 Using a Sentinel Value Sometimes the user has a very long list of input values, and doesn't know the exact number of items. A technique that can be used here is to ask the user to enter a sentinel value at the end of the list. A sentinel value is a special value that cannot be mistaken as a member of the list, and signals that there are no more values to be entered. When the user enters the sentinel value, the loop terminates.
63
63 Using a Sentinel Value
64
64 Using a Sentinel Value
65
65 7. Nested Loops Problem: Write a program to simulate a simple clock from 01:00:00 to 12:59:59 1 hour = 60 minutes 1 minute = 60 seconds
66
66 7. Nested Loops
67
67 7. Nested Loops A loop that is inside another loop is called a nested loop. A few points about nested loops: An inner loop goes through all of its iterations for each iteration of an outer loop. Inner loops complete their iterations before outer loops do. To get the total number of iterations of a nested loop, multiply the number of iterations of all the loops.
68
68 8. The break and continue Statements The break statement causes a loop to terminate early. The loop stops and the program jumps to the statement immediately following the loop. The continue statement causes a loop to stop its current iteration and begin the next one. All the statements in the body of the loop that appear after it are ignored, and the loop prepares for the next iteration.
69
69 8. The break and continue Statements 505025
70
70 9. Deciding Which Loop to Use The while loop It is a pretest loop. It is ideal in situations where you do not want the loop to iterate if the condition is false from the beginning. It is also ideal if you want to use a sentinel value to terminate the loop. The do-while loop It is a posttest loop. It is ideal in situations where you always want the loop to iterate at least once.
71
71 9. Deciding Which Loop to Use The for loop It is a pretest loop that has built-in expressions for initializing, testing, and updating. Very convenient to use a loop control variable as a counter It is ideal in situations where the exact number of iterations is known.
72
72 Checkpoint 4.13 4.14 4.15
73
73 10. Introduction to File Input and Output The Java API provides several classes that you can use for writing data to a file and reading data from a file. To write data to a file FileWriter PrintWriter To read data from a file FileReader BufferedReader
74
74 10. Introduction to File Input and Output Data may be saved in a file, which is usually stored on a computer's disk. In general, there are three steps that are taken when a file is used by a program 1.The file must be opened. When the file is opened, a connection is created between the file and the program. 2.Data is then written to the file or read from the file. 3.When the program is finished using the file, the file must be closed.
75
75 Input Files and Output Files An input file is a file that a program reads data from. It is called an input file because the data stored in it serves as input to the program. An output file is a file that a program writes data to. It is called an output file because the program stores output in the file.
76
76 Input Files and Output Files The file is opened The program reads data from the opened file. The file is closed Input file The file is opened The program writes data to the opened file. The file is closed Output file
77
77 Text Files and Binary Files A text file contains data that has been encoded as text, using a scheme such as Unicode. Even if the file contains numbers, those numbers are stored in the file as a series of characters. The file may be opened and viewed in a text editor. A binary file contains data that has not been converted to text. You can not view the contents of a binary file with a text editor. In this chapter, we will discuss how to work with text files.
78
78 Writing Data to a File To write data to a file, you must create objects from the following classes: FileWriter This class allows you to open a file for writing and establishing a connection with it. It provides only basic functionality for writing data to the file. PrintWriter This class allows you to write data to a file using the same print and println methods. The PrintWriter class by itself cannot directly access the file. It used in conjunction with a FileWriter object that has a connection to a file.
79
79 Writing Data to a File Open a file and establish a connection with it: FileWriter fwriter = new FileWriter(“StudentData.txt”); Creates an empty file named StudentData.txt and establishes a connection between the file and the FileWriter object. The file will be created in the current folder. If the file opened with the FileWriter object already exists, it will be erased and an empty file with the same name will be created.
80
80 Writing Data to a File We may also pass a reference to a String object as an argument to the FileWriter constructor String filename; Filename = JoptionPane.showInputDialog(“Enter the filename”); FileWriter fwriter = new FileWriter(filename);
81
81 Writing Data to a File Creating a PrintWriter object FileWriter fwriter = new FileWriter(“StudentData.txt”); PrintWriter outFile = new PrintWriter(fwriter); Using print and println methods to write data to a file FileWriter fwriter = new FileWriter(“StudentData.txt”); PrintWriter outFile = new PrintWriter(fwriter); outputFile.println(“Jim”);
82
82 Writing Data to a File When the program is finished writing data to the file, it must be closed. FileWriter fwriter = new FileWriter(“StudentData.txt”); PrintWriter outFile = new PrintWriter(fwriter); outputFile.println(“Jim”); outputFile.close();
83
83 Writing Data to a File The program should always close files when it's finished with them. When a program writes a file to a file, data is first written to the file's buffer. When the buffer is filled, all information stored there is written to the file. The close method writes any unsaved data remaining in the file's buffer. Once a file is closed, the connection between it and the FileWriter object is removed. In order to perform further operations on the file, it must be opened again.
84
84 The PrintWriter Class's println Method The PrintWriter class's println method writes a line of data to a file. Create a file named StudentData.txt and write two students' first names and their test scores to the file: FileWriter fwriter = new FileWriter(“StudentData.txt”); PrintWriter outFile = new PrintWriter(fwriter); outputFile.println(“Jim”); outputFile.println(95); outputFile.println(“Karen”); outputFile.println(98); outputFile.close();
85
85 The PrintWriter Class's println Method The println method writes data to a file and then writes a newline character immediately after the data. Jim 95 Karen 98 The newline characters are represented here as.
86
86 The PrintWriter Class's print Method The print method is used to write an item of data to a file without writing the newline character. String name = “Jeffrey Smith”; String phone = “555-7864”; int idNumber = 47895; FileWriter fwriter = new FileWriter(“PersonalData.txt”); PrintWriter outFile = new PrintWriter(fwriter); outputFile.print(name + “ “); outputFile.print(phone + “ “); outputFile.println(idNumber); outputFile.close();
87
87 Add a throws Clause to the Method Header Suppose that we create a FileWriter object, but unexpectedly, the disk is full and the file cannot be created. The program cannot continue until this situation has been dealt with, so an exception is thrown, which causes the program to suspend normal execution. When an unexpected event occurs in a Java program, it is said that the program throws an exception. An exception is a signal indicating that the program cannot continue until the unexpected even has been dealt with.
88
88 Add a throws Clause to the Method Header When an exception is thrown, the method that is executing must either deal with the exception or throw it again. If the main method throw an exception, the program halts and an error message is displayed. To allow a method to rethrow an exception that has not been dealt with, we simply write a throws clause in the method header.
89
89 Add a throws Clause to the Method Header public static void main(String[] args) throws IOException This header indicates that the main method is capable of throwing an exception of IOException type. The IOException type is the type of exception that FileWriter and PrintWriter objects are capable of throwing.
90
90 Writing Data to a File Problem: Write a Java program that allow the user to enter names of your friends and writes the names to a file.
91
91 Writing Data to a File
92
92 Writing Data to a File
93
93 Appending Data to a File To preserve an existing file and append new data to its current contents Appending to a file means to write new data to the end of the data that already exists in the file. The FileWriter constructor takes an optional second argument, which must be a boolean value: If the argument is true, the file will not be erased if it already exists and new data will be written to the end of the file. If it is false, the file will be erased if it already exists.
94
94 Appending Data to a File FileWriter fwriter = new FileWriter(“MyFriends.txt”,true); PrintWriter outFile = new PrintWriter(fwriter); If the file MyFriends.txt already exists, new data will be written to the end of the file. FileWriter fwriter = new FileWriter(“MyFriends.txt”,false); PrintWriter outFile = new PrintWriter(fwriter); If the file MyFriends.txt already exists, the file will be erased.
95
95 Review 1. You must have the import java.io.*; statement in the top section of your program. 2. Because we have not learned how to respond to exceptions, any method that uses a FileWriter or PrintWriter object must have a throws IOException clause in its header. 3. You create a FileWriter object and pass the name of the file as a string to the constructor.
96
96 Review 4. You create a PrintWriter object and pass a reference to the FileWriter object as an argument to the constructor. 5. You use the PrintWriter object's print and println methods to write data to the file. 6. When finished writing to the file, you use the PrintWriter object's close method to close the file.
97
97 Specifying the File Location Specifying the file location: FileWriter fwriter = new FileWriter(“C:\\Mydata\\StudentData.txt”); PrintWriter outFile = new PrintWriter(fwriter); Java allows you to substitute forward slashes for backward slashes in a Windows path. FileWriter fwriter = new FileWriter(“C:/MyData/StudentData.txt”); PrintWriter outFile = new PrintWriter(fwriter);
98
98 Reading Data from a File To read data from a file, you must create objects from the following classes: FileReader This class allows you to open a file for reading and establishing a connection with it. It provides only basic functionality for reading one character at a time from the file. BufferedReader This class allows you to read entire lines from a file. The BufferedReader class by itself cannot directly access the file. It used in conjunction with a FileReader object that has a connection to a file.
99
99 Reading Data from a File Opening a file for reading FileReader freader = new FileWriter(“Customers.txt”); BufferedReader inputFile = new BufferedReader(freader); Reading lines with the readLine method The readLine method is a member of the BufferedReader class, and is used to read a line of data from a file. The readLine method returns the line as a String.
100
100 Reading Data from a File The String that is returned from the readLine method will not contain the newline character. Consider the file Quatation.txt that has three lines Imagination is more important than knowledge. Albert Einstein You can visualize that the data is stored in the file in the following manner: Imagination is more important than knowledge. Albert Einstein
101
101 Reading Data from a File String line1, line2, line3; FileReader freader = new FileWriter(“Quotation.txt”); BufferedReader inputFile = new BufferedReader(freader); // The read position is at the beginning of the first line line1 = inputFile.readLine(); // The read position is advanced to the beginning of the second line line2 = inputFile.readLine(); // The read position is advanced to the beginning of the third line line3 = inputFile.readLine(); // The read position is at the end of the file
102
102 Add a throws Clause to the Method Header FileReader and BufferedReader objects can also throw exceptions of the IOException type. We need to write a throws IOException clause in the header of any method that uses these types of objects.
103
103 Closing the File When the program is finished reading data from the file, it should close the file. To close the file, use the BufferedReader class's close method. inputFile.close();
104
104 Detecting the End of a File Quite often a program must read the contents of a file without knowing the number of items that are stored in the file. The program must detect the end of the file. You can determine when the end of a file has been reached by testing the value returned from the readLine method. If the last item has been read and the end of the file has been reached, the readLine method return null.
105
105 Detecting the End of a File Did readLine return null ? No Yes Process the item Read the next item using the readLine method. Open the file. Read the first item using the readLine method. Close the file.
106
106 Detecting the End of a File FileReader freader = new FileWriter(filename); BufferedReader inputFile = new BufferedReader(freader); String str; // Read the first item. str = inputFile.readLine(); // If an item was read, display it and read the remaining // items. while(str != null) { System.out.println(str); str = inputFile.readLine(); } inputFile.Close();
107
107 Reading Data from a File Problem: Write a program that reads data from a text file. The file contains the names of your friends.
108
108 Reading Data from a File
109
109 Review 1. You must have the import java.io.*; statement in the top section of your program. 2. Because we have not learned how to respond to exceptions, any method that uses a FileReader or BufferedReader object must have a throws IOException clause in its header. 3. You create a FileReader object and pass the name of the file as a string to the constructor.
110
110 Review 4. You create a BufferedReader object and pass a reference to the FileReader object as an argument to the constructor. 5. You use the BufferedReader object's readLine method to read a linefrom the file. The method returns the line of data as a string. If the end of the file has been reached, the method returns null. 6. When finished reading from the file, you use the BufferedReader object's close method to close the file.
111
111 Converting String Values to Numbers Problem: Write a program that reads a text file Numbers.txt. The file contains a series of numbers. The program calculates the total of the numbers.
112
112 Converting String Values to Numbers
113
113 Checkpoint 4.16 4.17 4.18 4.19 4.20 4.21 4.22 4.23
114
114 11. The Random Class The Random class is used to generate a sequence of random numbers. Using Random class import java.util.Random; Random randomNumbers = new Random(); Use the Random class's method to generate random numbers.
115
115 11. The Random Class Some of the Random class's methods 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. nextInt(int n) : Returns the next random number as an int. The number will be within the range of 0 and n. nextLong() : Returns the next random number as a long.
116
116 11. The Random Class Problem: Write a Java program displays an addition problem, and allows the user to enter the answer. Then the program checks whether the answer is correct.
117
117
118
118
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.