archive-edu.com » EDU » H » HWS.EDU

Total: 727

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Javanotes 7.0, Section 3.1 -- Blocks, Loops, and Branches
    println Done The variable number is initialized with the value 1 So when the computer evaluates the expression number 6 for the first time it is asking whether 1 is less than 6 which is true The computer therefore proceeds to execute the two statements inside the loop The first statement prints out 1 The second statement adds 1 to number and stores the result back into the variable number the value of number has been changed to 2 The computer has reached the end of the loop so it returns to the beginning and asks again whether number is less than 6 Once again this is true so the computer executes the loop again this time printing out 2 as the value of number and then changing the value of number to 3 It continues in this way until eventually number becomes equal to 6 At that point the expression number 6 evaluates to false So the computer jumps past the end of the loop to the next statement and prints out the message Done Note that when the loop ends the value of number is 6 but the last value that was printed was 5 By the way you should remember that you ll never see a while loop standing by itself in a real program It will always be inside a subroutine which is itself defined inside some class As an example of a while loop used inside a complete program here is a little program that computes the interest on an investment over several years This is an improvement over examples from the previous chapter that just reported the results for one year This class implements a simple program that will compute the amount of interest that is earned on an investment over a period of 5 years The initial amount of the investment and the interest rate are input by the user The value of the investment at the end of each year is output public class Interest3 public static void main String args double principal The value of the investment double rate The annual interest rate Get the initial investment and interest rate from the user System out print Enter the initial investment principal TextIO getlnDouble System out println System out println Enter the annual interest rate System out print Enter a decimal not a percentage rate TextIO getlnDouble System out println Simulate the investment for 5 years int years Counts the number of years that have passed years 0 while years 5 double interest Interest for this year interest principal rate principal principal interest Add it to principal years years 1 Count the current year System out print The value of the investment after System out print years System out print years is System out printf 1 2f principal System out println end of while loop end of main end of class Interest3 You should study this program and make sure that you understand what the computer does step by step as it

    Original URL path: http://math.hws.edu/javanotes/c3/s1.html (2016-02-07)
    Open archived version from archive


  • Javanotes 7.0, Section 3.2 -- Algorithm Development
    a reasonably complete specification of the problem might look like in this example Write a program that will compute and display the value of an investment for each of the next five years Each year interest is added to the value The interest is computed by multiplying the current value by a fixed interest rate Assume that the initial value and the rate of interest are to be input by the user when the program is run 3 2 2 The 3N 1 Problem Let s do another example working this time with a program that you haven t already seen The assignment here is an abstract mathematical problem that is one of my favorite programming exercises This time we ll start with a more complete specification of the task to be performed Given a positive integer N define the 3N 1 sequence starting from N as follows If N is an even number then divide N by two but if N is odd then multiply N by 3 and add 1 Continue to generate numbers in this way until N becomes equal to 1 For example starting from N 3 which is odd we multiply by 3 and add 1 giving N 3 3 1 10 Then since N is even we divide by 2 giving N 10 2 5 We continue in this way stopping when we reach 1 The complete sequence is 3 10 5 16 8 4 2 1 Write a program that will read a positive integer from the user and will print out the 3N 1 sequence starting from that integer The program should also count and print out the number of terms in the sequence A general outline of the algorithm for the program we want is Get a positive integer N from the user Compute print and count each number in the sequence Output the number of terms The bulk of the program is in the second step We ll need a loop since we want to keep computing numbers until we get 1 To put this in terms appropriate for a while loop we need to know when to continue the loop rather than when to stop it We want to continue as long as the number is not 1 So we can expand our pseudocode algorithm to Get a positive integer N from the user while N is not 1 Compute N next term Output N Count this term Output the number of terms In order to compute the next term the computer must take different actions depending on whether N is even or odd We need an if statement to decide between the two cases Get a positive integer N from the user while N is not 1 if N is even Compute N N 2 else Compute N 3 N 1 Output N Count this term Output the number of terms We are almost there The one problem that remains is counting Counting means that you start with zero and every time you have something to count you add one We need a variable to do the counting The variable must be set to zero once before the loop starts and it must be incremented within the loop Again this is a common pattern that you should expect to see over and over With the counter added we get Get a positive integer N from the user Let counter 0 while N is not 1 if N is even Compute N N 2 else Compute N 3 N 1 Output N Add 1 to counter Output the counter We still have to worry about the very first step How can we get a positive integer from the user If we just read in a number it s possible that the user might type in a negative number or zero If you follow what happens when the value of N is negative or zero you ll see that the program will go on forever since the value of N will never become equal to 1 This is bad In this case the problem is probably no big deal but in general you should try to write programs that are foolproof One way to fix this is to keep reading in numbers until the user types in a positive number Ask user to input a positive number Let N be the user s response while N is not positive Print an error message Read another value for N Let counter 0 while N is not 1 if N is even Compute N N 2 else Compute N 3 N 1 Output N Add 1 to counter Output the counter The first while loop will end only when N is a positive number as required A common beginning programmer s error is to use an if statement instead of a while statement here If N is not positive ask the user to input another value The problem arises if the second number input by the user is also non positive The if statement is only executed once so the second input number is never tested and the program proceeds into an infinite loop With the while loop after the second number is input the computer jumps back to the beginning of the loop and tests whether the second number is positive If not it asks the user for a third number and it will continue asking for numbers until the user enters an acceptable input After the while loop ends we can be absolutely sure that N is a positive number Here is a Java program implementing this algorithm It uses the operators to mean is less than or equal to and to mean is not equal to To test whether N is even it uses N 2 0 All the operators used here were discussed in Section 2 5 This program prints out a 3N 1 sequence starting from a positive integer specified by the user It also counts the

    Original URL path: http://math.hws.edu/javanotes/c3/s2.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 3.3 -- The while and do..while Statements
    the user s input is positive so it will actually add up both positive and negative input values public class ComputeAverage public static void main String args int inputNumber One of the integers input by the user int sum The sum of the positive integers int count The number of positive integers double average The average of the positive integers Initialize the summation and counting variables sum 0 count 0 Read and process the user s input System out print Enter your first positive integer inputNumber TextIO getlnInt while inputNumber 0 sum inputNumber Add inputNumber to running sum count Count the input by adding 1 to count System out print Enter your next positive integer or 0 to end inputNumber TextIO getlnInt Display the result if count 0 System out println You didn t enter any data else average double sum count System out println System out println You entered count positive integers System out printf Their average is 1 3f n average end main end class ComputeAverage 3 3 2 The do while Statement Sometimes it is more convenient to test the continuation condition at the end of a loop instead of at the beginning as is done in the while loop The do while statement is very similar to the while statement except that the word while along with the condition that it tests has been moved to the end The word do is added to mark the beginning of the loop A do while statement has the form do statement while boolean expression or since as usual the statement can be a block do statements while boolean expression Note the semicolon at the very end This semicolon is part of the statement just as the semicolon at the end of an assignment statement or declaration is part of the statement Omitting it is a syntax error More generally every statement in Java ends either with a semicolon or a right brace To execute a do loop the computer first executes the body of the loop that is the statement or statements inside the loop and then it evaluates the boolean expression If the value of the expression is true the computer returns to the beginning of the do loop and repeats the process if the value is false it ends the loop and continues with the next part of the program Since the condition is not tested until the end of the loop the body of a do loop is always executed at least once For example consider the following pseudocode for a game playing program The do loop makes sense here instead of a while loop because with the do loop you know there will be at least one game Also the test that is used at the end of the loop wouldn t even make sense at the beginning do Play a Game Ask user if he wants to play another game Read the user s response while the user s response is yes Let

    Original URL path: http://math.hws.edu/javanotes/c3/s3.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 3.4 -- The for Statement
    like any statement except for a variable declaration never occurs on its own in a real program A statement must be inside the main routine of a program or inside some other subroutine And that subroutine must be defined inside a class I should also remind you that every variable must be declared before it can be used and that includes the loop control variable in a for statement In all the examples that you have seen so far in this section the loop control variables should be declared to be of type int It is not required that a loop control variable be an integer Here for example is a for loop in which the variable ch is of type char using the fact that the operator can be applied to characters as well as to numbers Print out the alphabet on one line of output char ch The loop control variable one of the letters to be printed for ch A ch Z ch System out print ch System out println 3 4 2 Example Counting Divisors Let s look at a less trivial problem that can be solved with a for loop If N and D are positive integers we say that D is a divisor of N if the remainder when D is divided into N is zero Equivalently we could say that N is an even multiple of D In terms of Java programming D is a divisor of N if N D is zero Let s write a program that inputs a positive integer N from the user and computes how many different divisors N has The numbers that could possibly be divisors of N are 1 2 N To compute the number of divisors of N we can just test each possible divisor of N and count the ones that actually do divide N evenly In pseudocode the algorithm takes the form Get a positive integer N from the user Let divisorCount 0 for each number testDivisor in the range from 1 to N if testDivisor is a divisor of N Count it by adding 1 to divisorCount Output the count This algorithm displays a common programming pattern that is used when some but not all of a sequence of items are to be processed The general pattern is for each item in the sequence if the item passes the test process it The for loop in our divisor counting algorithm can be translated into Java code as for testDivisor 1 testDivisor N testDivisor if N testDivisor 0 divisorCount On a modern computer this loop can be executed very quickly It is not impossible to run it even for the largest legal int value 2147483647 If you wanted to run it for even larger values you could use variables of type long rather than int However it does take a significant amount of time for very large numbers So when I implemented this algorithm I decided to output a dot every time the computer has tested one million possible divisors In the improved version of the program there are two types of counting going on We have to count the number of divisors and we also have to count the number of possible divisors that have been tested So the program needs two counters When the second counter reaches 1000000 the program outputs a and resets the counter to zero so that we can start counting the next group of one million Reverting to pseudocode the algorithm now looks like Get a positive integer N from the user Let divisorCount 0 Number of divisors found Let numberTested 0 Number of possible divisors tested since the last period was output for each number testDivisor in the range from 1 to N if testDivisor is a divisor of N Count it by adding 1 to divisorCount Add 1 to numberTested if numberTested is 1000000 print out a Reset numberTested to 0 Output the count Finally we can translate the algorithm into a complete Java program This program reads a positive integer from the user It counts how many divisors that number has and then it prints the result public class CountDivisors public static void main String args int N A positive integer entered by the user Divisors of this number will be counted int testDivisor A number between 1 and N that is a possible divisor of N int divisorCount Number of divisors of N that have been found int numberTested Used to count how many possible divisors of N have been tested When the number reaches 1000000 a period is output and the value of numberTested is reset to zero Get a positive integer from the user while true System out print Enter a positive integer N TextIO getlnInt if N 0 break System out println That number is not positive Please try again Count the divisors printing a after every 1000000 tests divisorCount 0 numberTested 0 for testDivisor 1 testDivisor N testDivisor if N testDivisor 0 divisorCount numberTested if numberTested 1000000 System out print numberTested 0 Display the result System out println System out println The number of divisors of N is divisorCount end main end class CountDivisors 3 4 3 Nested for Loops Control structures in Java are statements that contain other simpler statements In particular control structures can contain control structures You ve already seen several examples of if statements inside loops and one example of a while loop inside another while but any combination of one control structure inside another is possible We say that one structure is nested inside another You can even have multiple levels of nesting such as a while loop inside an if statement inside another while loop The syntax of Java does not set a limit on the number of levels of nesting As a practical matter though it s difficult to understand a program that has more than a few levels of nesting Nested for loops arise naturally in many algorithms and it is

    Original URL path: http://math.hws.edu/javanotes/c3/s4.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 3.5 -- The if Statement
    out println z x y You might check that this code will work correctly even if some of the values are the same If the values of two variables are the same it doesn t matter which order you print them in Note by the way that even though you can say in English if x is less than y and z you can t say in Java if x y z The operator can only be used between boolean values so you have to make separate tests x y and x z and then combine the two tests with There is an alternative approach to this problem that begins by asking which order should x and y be printed in Once that s known you only have to decide where to stick in z This line of thought leads to different Java code if x y x comes before y if z x z comes first System out println z x y else if z y z comes last System out println x y z else z is in the middle System out println x z y else y comes before x if z y z comes first System out println z y x else if z x z comes last System out println y x z else z is in the middle System out println y z x Once again we see how the same problem can be solved in many different ways The two approaches to this problem have not exhausted all the possibilities For example you might start by testing whether x is greater than y If so you could swap their values Once you ve done that you know that x should be printed before y Finally let s write a complete program that uses an if statement in an interesting way I want a program that will convert measurements of length from one unit of measurement to another such as miles to yards or inches to feet So far the problem is extremely under specified Let s say that the program will only deal with measurements in inches feet yards and miles It would be easy to extend it later to deal with other units The user will type in a measurement in one of these units such as 17 feet or 2 73 miles The output will show the length in terms of each of the four units of measure This is easier than asking the user which units to use in the output An outline of the process is Read the user s input measurement and units of measure Express the measurement in inches feet yards and miles Display the four results The program can read both parts of the user s input from the same line by using TextIO getDouble to read the numerical measurement and TextIO getlnWord to read the unit of measure The conversion into different units of measure can be simplified by first converting the user s input

    Original URL path: http://math.hws.edu/javanotes/c3/s5.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 3.7 -- Introduction to Exceptions and try..catch
    of the program the exception has been caught and handled and does not crash the program By the way note that the braces and are part of the syntax of the try catch statement They are required even if there is only one statement between the braces This is different from the other statements we have seen where the braces around a single statement are optional As an example suppose that str is a variable of type String whose value might or might not represent a legal real number Then we could say double x try x Double parseDouble str System out println The number is x catch NumberFormatException e System out println Not a legal number x Double NaN If an error is thrown by the call to Double parseDouble str then the output statement in the try part is skipped and the statement in the catch part is executed In this example I set x to be the value Double NaN when an exception occurs Double NaN is the special not a number value for type double It s not always a good idea to catch exceptions and continue with the program Often that can just lead to an even bigger mess later on and it might be better just to let the exception crash the program at the point where it occurs However sometimes it s possible to recover from an error Suppose for example we want a program that will find the average of a sequence of real numbers entered by the user and we want the user to signal the end of the sequence by entering a blank line This is similar to the sample program ComputeAverage java from Section 3 3 but in that program the user entered a zero to signal end of input If we use TextIO getlnInt to read the user s input we will have no way of detecting the blank line since that function simply skips over blank lines A solution is to use TextIO getln to read the user s input This allows us to detect a blank input line and we can convert non blank inputs to numbers using Double parseDouble And we can use try catch to avoid crashing the program when the user s input is not a legal number Here s the program public class ComputeAverage2 public static void main String args String str The user s input double number The input converted into a number double total The total of all numbers entered double avg The average of the numbers int count The number of numbers entered total 0 count 0 System out println Enter your numbers press return to end while true System out print str TextIO getln if str equals break Exit the loop since the input line was blank try number Double parseDouble str If an error occurs the next 2 lines are skipped total total number count count 1 catch NumberFormatException e System out println Not a legal number

    Original URL path: http://math.hws.edu/javanotes/c3/s7.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 3.8 -- Introduction to Arrays
    the largest number in the array A The strategy is to go through the array keeping track of the largest number found so far We ll store the largest number found so far in a variable called max As we look through the array whenever we find a number larger than the current value of max we change the value of max to that larger value After the whole array has been processed max is the largest item in the array overall The only question is what should the original value of max be One possibility is to start with max equal to A 0 and then to look through the rest of the array starting from A 1 for larger items double max The largest number seen so far max A 0 At first the largest number seen is A 0 int i for i 1 i A length i if A i max max A i at this point max is the largest item in A Sometimes you only want to process some elements of the array In that case you can use an if statement inside the for loop to decide whether or not to process a given element Let s look at the problem of averaging the elements of an array but this time suppose that we only want to average the non zero elements In this case the number of items that we add up can be less than the length of the array so we will need to keep a count of the number of items added to the sum double total The sum of the non zero numbers in the array int count The number of non zero numbers double average The average of the non zero numbers int i total 0 count 0 for i 0 i A length i if A i 0 total total A i Add element to the total count count 1 and count it if count 0 System out println There were no non zero elements else average total count Divide by number of items System out printf Average of d elements is 1 5g n count average 3 8 3 Random Access So far my examples of array processing have used sequential access That is the elements of the array were processed one after the other in the sequence in which they occur in the array But one of the big advantages of arrays is that they allow random access That is every element of the array is equally accessible at any given time As an example let s look at a well known problem called the birthday problem Suppose that there are N people in a room What s the chance that there are two people in the room who have the same birthday That is they were born on the same day in the same month but not necessarily in the same year Most people severely underestimate the probability We will actually look at a different version of the question Suppose you choose people at random and check their birthdays How many people will you check before you find one who has the same birthday as someone you ve already checked Of course the answer in a particular case depends on random factors but we can simulate the experiment with a computer program and run the program several times to get an idea of how many people need to be checked on average To simulate the experiment we need to keep track of each birthday that we find There are 365 different possible birthdays We ll ignore leap years For each possible birthday we need to keep track of whether or not we have already found a person who has that birthday The answer to this question is a boolean value true or false To hold the data for all 365 possible birthdays we can use an array of 365 boolean values boolean used used new boolean 365 For this problem the days of the year are numbered from 0 to 364 The value of used i is true if someone has been selected whose birthday is day number i Initially all the values in the array are false Remember that this is done automatically when the array is created When we select someone whose birthday is day number i we first check whether used i is true If it is true then this is the second person with that birthday We are done On the other hand if used i is false we set used i to be true to record the fact that we ve encountered someone with that birthday and we go on to the next person Here is a program that carries out the simulated experiment of course in the program there are no simulated people only simulated birthdays Simulate choosing people at random and checking the day of the year they were born on If the birthday is the same as one that was seen previously stop and output the number of people who were checked public class BirthdayProblem public static void main String args boolean used For recording the possible birthdays that have been seen so far A value of true in used i means that a person whose birthday is the i th day of the year has been found int count The number of people who have been checked used new boolean 365 Initially all entries are false count 0 while true Select a birthday at random from 0 to 364 If the birthday has already been used quit Otherwise record the birthday as used int birthday The selected birthday birthday int Math random 365 count System out printf Person d has birthday number d count birthday System out println if used birthday This day was found before it s a duplicate We are done break used birthday true end while System out println System out println A duplicate birthday was found after count tries end

    Original URL path: http://math.hws.edu/javanotes/c3/s8.html (2016-02-07)
    Open archived version from archive

  • Javanotes 7.0, Section 4.2 -- Static Subroutines and Static Variables
    call playGame from outside the Poker class you would have to say Poker playGame The use of the class name here tells the computer which class to look in to find the method It also lets you distinguish between Poker playGame and other potential playGame methods defined in other classes such as Roulette playGame or Blackjack playGame More generally a subroutine call statement for a static subroutine takes the form subroutine name parameters if the subroutine that is being called is in the same class or class name subroutine name parameters if the subroutine is defined elsewhere in a different class Non static methods belong to objects rather than classes and they are called using objects instead of class names More on that later Note that the parameter list can be empty as in the playGame example but the parentheses must be there even if there is nothing between them The number of parameters that you provide when you call a subroutine must match the number listed in the parameter list in the subroutine definition and the types of the parameters in the call statement must match the types in the subroutine definition 4 2 3 Subroutines in Programs It s time to give an example of what a complete program looks like when it includes other subroutines in addition to the main routine Let s write a program that plays a guessing game with the user The computer will choose a random number between 1 and 100 and the user will try to guess it The computer tells the user whether the guess is high or low or correct If the user gets the number after six guesses or fewer the user wins the game After each game the user has the option of continuing with another game Since playing one game can be thought of as a single coherent task it makes sense to write a subroutine that will play one guessing game with the user The main routine will use a loop to call the playGame subroutine over and over as many times as the user wants to play We approach the problem of designing the playGame subroutine the same way we write a main routine Start with an outline of the algorithm and apply stepwise refinement Here is a short pseudocode algorithm for a guessing game routine Pick a random number while the game is not over Get the user s guess Tell the user whether the guess is high low or correct The test for whether the game is over is complicated since the game ends if either the user makes a correct guess or the number of guesses is six As in many cases the easiest thing to do is to use a while true loop and use break to end the loop whenever we find a reason to do so Also if we are going to end the game after six guesses we ll have to keep track of the number of guesses that the user has made Filling out the algorithm gives Let computersNumber be a random number between 1 and 100 Let guessCount 0 while true Get the user s guess Count the guess by adding 1 to guess count if the user s guess equals computersNumber Tell the user he won break out of the loop if the number of guesses is 6 Tell the user he lost break out of the loop if the user s guess is less than computersNumber Tell the user the guess was low else if the user s guess is higher than computersNumber Tell the user the guess was high With variable declarations added and translated into Java this becomes the definition of the playGame routine A random integer between 1 and 100 can be computed as int 100 Math random 1 I ve cleaned up the interaction with the user to make it flow better static void playGame int computersNumber A random number picked by the computer int usersGuess A number entered by user as a guess int guessCount Number of guesses the user has made computersNumber int 100 Math random 1 The value assigned to computersNumber is a randomly chosen integer between 1 and 100 inclusive guessCount 0 System out println System out print What is your first guess while true usersGuess TextIO getInt Get the user s guess guessCount if usersGuess computersNumber System out println You got it in guessCount guesses My number was computersNumber break The game is over the user has won if guessCount 6 System out println You didn t get the number in 6 guesses System out println You lose My number was computersNumber break The game is over the user has lost If we get to this point the game continues Tell the user if the guess was too high or too low if usersGuess computersNumber System out print That s too low Try again else if usersGuess computersNumber System out print That s too high Try again System out println end of playGame Now where exactly should you put this It should be part of the same class as the main routine but not inside the main routine It is not legal to have one subroutine physically nested inside another The main routine will call playGame but not contain its definition only a call statement You can put the definition of playGame either before or after the main routine Java is not very picky about having the members of a class in any particular order It s pretty easy to write the main routine You ve done things like this before Here s what the complete program looks like except that a serious program needs more comments than I ve included here public class GuessingGame public static void main String args System out println Let s play a game I ll pick a number between System out println 1 and 100 and you try to guess it boolean playAgain do playGame call subroutine to play

    Original URL path: http://math.hws.edu/javanotes/c4/s2.html (2016-02-07)
    Open archived version from archive