text
stringlengths
1
7.76k
source
stringlengths
17
81
29. Methods 16 System.out.println("main: b = " + b); 17 18 change(a, b); 19 20 System.out.println("main after: s = " + a); 21 System.out.println("main after: b = " + b); 22 23 } 24 } To see this, observe the following output. When we return to the main method, the original string s is unchanged (since it was immutable)...
ComputerScienceOne_Page_462_Chunk2001
29.2. Examples on. We could demonstrate good code reuse (as well as good procedural abstraction) by scaling the input value and reusing the functionality already provided in the math library’s Math.round() method. We could further define a roundToCents() method that used our generalized round method. Finally, we could p...
ComputerScienceOne_Page_463_Chunk2002
29. Methods is not executable itself. It only provides functionality to other classes in the code base. 430
ComputerScienceOne_Page_464_Chunk2003
30. Error Handling & Exceptions Java supports error handling through the use of exceptions. Java has many different predefined types of exceptions that you can use in your own code. It also allows you to define your own exception types by creating new classes that inherit from the predefined classes. Java uses the standard...
ComputerScienceOne_Page_465_Chunk2004
30. Error Handling & Exceptions 4 try { 5 String input = s.next(); 6 n = Integer.parseInt(input); 7 } catch (NumberFormatException nfe) { 8 System.err.println("You entered invalid data!"); 9 System.exit(1); 10 } In this example, we’ve simply displayed an error message to the standard error output and exited the program...
ComputerScienceOne_Page_466_Chunk2005
30.1. Exceptions Note that the last catch block was written to catch a generic Exception . This last block will essentially catch any other type of exception. Much like an if-else-if statement, the first type of exception that is caught is the block that will be executed and they are all mutually exclusive. Thus, a “cat...
ComputerScienceOne_Page_467_Chunk2006
30. Error Handling & Exceptions Now in our code we can throw and catch this new type of exception. 1 //throw this exception: 2 if( b*b - 4*a*c < 0) { 3 throw new ComplexRootException("Cannot Handle complex roots"); 4 } 1 try { 2 r1 = getComplexRoot01(a, b, c); 3 } catch(ComplexRootException cre) { 4 //handle the except...
ComputerScienceOne_Page_468_Chunk2007
30.1. Exceptions 6 //handle the exception here 7 } 8 } or we would need to specify that the method processFile() explicitly throws the exception: 1 public static void processFile() throws FileNotFoundException { 2 Scanner s = new Scanner(new File("data.csv")); 3 } Doing this, however, would force any code that called t...
ComputerScienceOne_Page_469_Chunk2008
30. Error Handling & Exceptions exceptions were a mistake and their usage should be avoided. The rationale behind checked exceptions is summed up in the following quote from the Java documentation [7]. Here’s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a check...
ComputerScienceOne_Page_470_Chunk2009
30.2. Enumerated Types 8 SATURDAY; 9 } In the example, since the name of the enumeration is Day this declaration must be in a source file named Day.java . We can now declare variables of this type. The possible values it can take are restricted to SUNDAY , MONDAY , etc. and we can use these keywords in our program. Howe...
ComputerScienceOne_Page_471_Chunk2010
30. Error Handling & Exceptions 1 for(Day d : Day.values() { 2 System.out.println(d.name()); 3 } In the example above, we used another feature: each enum value has a name() method that returns the value as a String . This example would end up printing the following. SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATUR...
ComputerScienceOne_Page_472_Chunk2011
31. Arrays Java allows you to declare and use arrays. Since Java is statically typed, arrays must also be typed when they are declared and may only hold that particular type of element. Since Java has automated garbage collection, memory management is greatly simplified. Finally, in Java, only locally scoped primitives ...
ComputerScienceOne_Page_473_Chunk2012
31. Arrays Each of these initializations creates a new array (allocated on the heap) of the specified size (10, 20, and 5 respectively). These arrays can only hold values of the specified type, int , double , and String respectively. The default value for each element in these new arrays will be zero for the numeric type...
ComputerScienceOne_Page_474_Chunk2013
31.1. Basic Usage catch and handle if you choose. To prevent such an exception you can write code that does not exceed the bounds of the array. Java arrays have a special length property that gives you the size of the array. You can access the property using the dot operator, so arr.length would give the value 5 for th...
ComputerScienceOne_Page_475_Chunk2014
31. Arrays 31.2. Dynamic Memory The use of the keyword new dynamically allocates memory space (on the heap) for the array. Because Java has automated garbage collection, if the reference to the array goes out of scope, it is automatically cleaned up by the JVM. This process is automated and essentially transparent to u...
ComputerScienceOne_Page_476_Chunk2015
31.4. Multidimensional Arrays In Java, arrays are always passed by reference. Though we did not make any changes to the contents of the passed array in the particular example, in general we could have. Any such changes would be realized in the calling method. Unfortunately, there is no mechanism by which we can prevent...
ComputerScienceOne_Page_477_Chunk2016
31. Arrays This creates a 2-dimensional array of integers with 10 rows and 20 columns. Once created, we can index individual elements by specifying row and column indices. 1 for(int i=0; i<matrix.length; i++) { 2 for(int j=0; j<matrix[i].length; j++) { 3 matrix[i][j] = 10; 4 } 5 } 31.5. Dynamic Data Structures The Java...
ComputerScienceOne_Page_478_Chunk2017
31.5. Dynamic Data Structures would be a compiler error to attempt to add anything other than Integer s to the first list or anything other than String s to the second. Once these lists have been created, you can add and remove elements using the add() method. 1 a.add(42); 2 a.add(81); 3 a.add(17); 4 5 b.add("Hello"); 6...
ComputerScienceOne_Page_479_Chunk2018
31. Arrays Any attempt to access an element that lies outside the bounds of the List , will result in an IndexOutOfBoundsException just as with arrays. To stay within bounds you can use the size() method to determine how many elements are in the collection. In this example, values.size() would return an integer value o...
ComputerScienceOne_Page_480_Chunk2019
31.5. Dynamic Data Structures 3 } When this code executes we cannot expect any particular order of the three names. Any permutation of the three may be printed. If we executed the loop more than once we may even observe a different enumeration of the names! Finally, Java also supports a Map data structure which allows y...
ComputerScienceOne_Page_481_Chunk2020
32. Strings As we’ve previously seen, Java has a String class in the standard JDK. Internally, Java strings are stored as arrays of characters. However, because of the String class, we never directly interact with this representation. Making using strings much easier than in other languages. Java strings have also supp...
ComputerScienceOne_Page_483_Chunk2021
32. Strings charAt() method and providing an index. Characters in a string are 0-indexed just as with elements in arrays. 1 String fullName = "Tom Waits"; 2 //access individual characters: 3 char firstInitial = fullName.charAt(0); //'T' 4 char lastInitial = fullName.charAt(4); //'W' 5 6 if(fullName.charAt(8) == 's') { ...
ComputerScienceOne_Page_484_Chunk2022
32.2. String Methods 5 //or we can use toCharArray and an enhanced for loop: 6 for(char c : fullName.toCharArray()) { 7 System.out.println(c); 8 } Concatenation Java has a concatenation operator built into the language. The familiar plus sign, + can be used to combine one or more strings by appending them to each other...
ComputerScienceOne_Page_485_Chunk2023
32. Strings 1 String firstName = "Tom"; 2 String lastName = "Waits"; 3 4 String formattedName = new StringBuilder(lastName) 5 .append(", ") 6 .append(firstName) 7 .toString(); You can also use the StringBuilder class yourself directly. Computing a Substring There are two methods that allow you to compute a substring of...
ComputerScienceOne_Page_486_Chunk2024
32.4. Comparisons We can create our own arrays of strings similar to how we created arrays of int and double types. 1 //create an array that can hold 5 strings 2 String names[] = new String[5]; 3 4 names[0] = "Margaret Hamilton"; 5 names[1] = "Ada Lovelace"; 6 names[2] = "Grace Hopper"; 7 names[3] = "Marie Curie"; 8 na...
ComputerScienceOne_Page_487_Chunk2025
32. Strings 6 } The code above will not print anything even though the strings a and b have the same content. This is because a == b is comparing the memory address of the two variables. Since they point to different memory addresses (created by two separate calls to the constructors) they will not be equal. Instead, th...
ComputerScienceOne_Page_488_Chunk2026
32.5. Tokenizing 1 String a = "apple"; 2 String b = "apple"; 3 String c = "Hello"; 4 5 boolean result; 6 result = a.equals(b); //true 7 result = a.equals(c); //false 32.5. Tokenizing Recall that tokenizing is the process of splitting up a string using some delimiter. For example, the comma delimited string, "Smith,Joe,...
ComputerScienceOne_Page_489_Chunk2027
32. Strings 1 String s = "Alpha Beta \t Gamma \n Delta \t\nEpsilon"; 2 String tokens[] = s.split("[\\s]+"); 3 //tokens is now { "Alpha", "Beta", "Gamma", "Delta", "Epsilon" } 456
ComputerScienceOne_Page_490_Chunk2028
33. File I/O Java provides several different classes and utilities that support manipulating and pro- cessing files. In general, most file operations may result in an IOException , a checked exception that must be caught and handled. 33.1. File Input Though there are several ways that you can do file input, the easiest is ...
ComputerScienceOne_Page_491_Chunk2029
33. File I/O 1 String line; 2 while(s.hasNext()) { 3 line = s.nextLine(); 4 //process the line 5 } Once we are done reading the file, we can close the Scanner to free up resources: s.close(); . We could have placed all this code within one large try-catch block with perhaps a finally block to close the Scanner once were...
ComputerScienceOne_Page_492_Chunk2030
33.2. File Output 33.2. File Output There are several ways to achieve file output, but we’ll look at the simplest and most useful way. Java provides a PrintWriter class which offers many convenient methods for writing primitive and String types in a formatted manner. It has the usual print() and println() methods that we...
ComputerScienceOne_Page_493_Chunk2031
33. File I/O However, if necessary, binary output can be done using a FileOutputStream . Typically, you can load all your data into a byte array and dump it all at once. 1 byte data[] = ...; 2 try (FileOutputStream fos = 3 new FileOutputStream(new File("outfile.bin")) ){ 4 fos.write(data); 5 } catch(IOException ioe) { ...
ComputerScienceOne_Page_494_Chunk2032
34. Objects Java is a class-based object-oriented programming language, meaning that it facilitates the creation of objects through the use of classes. Classes are essentially “blueprints” for creating instances of objects. We’ve been implicitly using classes all along since everything in Java is a class or belongs to ...
ComputerScienceOne_Page_495_Chunk2033
34. Objects Recall that a package declaration allows you to organize classes and code within a package (directory) hierarchy. Moreover, source code for a class must be in a source file with the same name (and is case sensitive) with the .java extension. Our Student class would need to be in a file named Student.java and ...
ComputerScienceOne_Page_496_Chunk2034
34.2. Methods code (through reflection2 or other means) and the values of variables can be accessed or modified. Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N none (default) Y Y N N private Y N N N Table 34.1.: Java Visibility Keywords & Access Levels We now update our class declaration to incorpo...
ComputerScienceOne_Page_497_Chunk2035
34. Objects In contrast to the methods we defined in Chapter 29, when defining a member method, we do not use the static keyword. Making a variable or a method static means that the method belongs to the class and not to instances of the class. We add to our example by providing two public methods that compute and return...
ComputerScienceOne_Page_498_Chunk2036
34.2. Methods or mutate (that is, change) an instance’s variables, we can define accessor and mutator methods (or just simply getter and setter methods) to facilitate this. Each getter method returns the value of the instance’s variable while each setter method takes a value and sets the instance’s variable to the new v...
ComputerScienceOne_Page_499_Chunk2037
34. Objects 1 public String getFirstName() { 2 return this.firstName; 3 } 4 5 public void setFirstName(String firstName) { 6 this.firstName = firstName; 7 } One advantage to using getters and setters (as opposed to naively making everything public ) is that you can have greater control over the values that your variabl...
ComputerScienceOne_Page_500_Chunk2038
34.3. Constructors the class in a multithreaded program without having to worry about threads changing the state of instances on one another. Immutable classes are also safer to use in certain collections such as a Set . Elements in a Set are unique; attempting to add a duplicate element will have no effect on the Set ....
ComputerScienceOne_Page_501_Chunk2039
34. Objects 5 this.gpa = 0.0; 6 } Alternatively, we can define constructors that accept a subset of variable values. 1 public Student(String firstName, String lastName) { 2 this.firstName = firstName; 3 this.lastName = lastName; 4 this.id = 0; 5 this.gpa = 0.0; 6 } In both of these examples, we repeated a lot of code. O...
ComputerScienceOne_Page_502_Chunk2040
34.4. Usage 34.4. Usage Once we have defined our class and its constructors, we can create and use instances of it. Just as with regular variables, we need to declare instances of a class by providing the type and a variable name. For example: 1 Student s = null; 2 Student t = null; Both of these declarations are simply...
ComputerScienceOne_Page_503_Chunk2041
34. Objects The toString() method returns a String representation of the object. However, the default behavior that all classes inherit from the Object class is that it returns a string containing the fully qualified class name (package and class name) along with a hexadeci- mal representation of the JVM memory address ...
ComputerScienceOne_Page_504_Chunk2042
34.5. Common Methods this reason, many IDEs provide functionality to automatically generate such methods. The following example was generated by an IDE. 1 public boolean equals(Object obj) { 2 if (this == obj) { 3 return true; 4 } 5 if (obj == null) { 6 return false; 7 } 8 if (!(obj instanceof Student)) { 9 return fals...
ComputerScienceOne_Page_505_Chunk2043
34. Objects if two instances are equal (that is, equals() returns true ) then they must have the same hashCode() value. This requirement is necessary to ensure that hash table-based data structures operate properly. It is okay if unequal objects have equal or unequal hash values. This rule only applies when the objects...
ComputerScienceOne_Page_506_Chunk2044
34.6. Composition We can take this concept further and design our classes to own collections of other classes. For example, we could define a Course class and then update our Student class to own a collection of Course objects representing a student’s class schedule (this type of collection ownership is sometimes referr...
ComputerScienceOne_Page_507_Chunk2045
34. Objects Alternatively, we could make our design a bit more flexible by allowing the construction of a Student instance without having to provide a course schedule. Instead, we could add a method that allowed the outside code to add a course to the schedule . Something like the following. 1 public void addCourse(Cour...
ComputerScienceOne_Page_508_Chunk2046
34.7. Example 1 package unl.cse; 2 3 public class Student { 4 5 private String firstName; 6 private String lastName; 7 private int id; 8 private double gpa; 9 10 public Student(String firstName, String lastName, int id, double gpa) { 11 this.firstName = firstName; 12 this.lastName = lastName; 13 this.id = id; 14 this.g...
ComputerScienceOne_Page_509_Chunk2047
34. Objects 47 } 48 49 /** 50 * Scales the GPA, which is assumed to be on a 51 * 4.0 scale to a percentage. 52 */ 53 public double getGpaAsPercentage() { 54 return gpa / 4.0; 55 } 56 57 @Override 58 public String toString() { 59 return String.format("%s, %s (ID = %d); %.2f", 60 this.lastName, 61 this.firstName, 62 this...
ComputerScienceOne_Page_510_Chunk2048
34.7. Example 93 if (other.firstName != null) { 94 return false; 95 } 96 } else if (!firstName.equals(other.firstName)) { 97 return false; 98 } 99 if (Double.doubleToLongBits(gpa) != Double.doubleToLongBits(other.gpa)) { 100 return false; 101 } 102 if (id != other.id) { 103 return false; 104 } 105 if (lastName == null)...
ComputerScienceOne_Page_511_Chunk2049
35. Recursion Java supports recursion with no special syntax necessary. However, as an object-oriented language, recursion is generally expensive and iterative or other non-recursive solutions are generally preferred. We present a few examples to demonstrate how to write recursive methods in Java. The first example of a...
ComputerScienceOne_Page_513_Chunk2050
35. Recursion the recursive method call. 1 public static int recSumTail(int arr[], int i, int sum) { 2 if(i == arr.length) { 3 return sum; 4 } else { 5 return recSumTail(arr, i+1, sum + arr[i]); 6 } 7 } As another example, consider the following Java implementation of the naive recursive Fibonacci sequence. An addition...
ComputerScienceOne_Page_514_Chunk2051
14 return result; 15 } 16 } Java provides an arbitrary precision data type, BigInteger that can be used to compute arbitrarily large integer values. Since Fibonacci numbers grow exponentially, using an int we could only represent up to to F45. Using BigInteger we can support much larger values. An example: 1 public sta...
ComputerScienceOne_Page_515_Chunk2052
36. Searching & Sorting Java provides several methods to search and sort arrays as well as List s of elements of any type. These methods are able to operate on collections of any type because there are several overloaded versions of these functions as well as versions that take a Comparator object that specifies how the...
ComputerScienceOne_Page_517_Chunk2053
36. Searching & Sorting something similar, the Comparable interface, that specifies a compareTo() method with the same basic contract. Strings for example, are ordered in lexicographic ordering. Numeric types such as Integer and Double also have compareTo() methods that order elements in ascending order. Java refers to ...
ComputerScienceOne_Page_518_Chunk2054
36.1. Comparators this issue by rearranging our cases so that the equality is our final case, avoiding the use of the equality operator. Even better, however, we can exploit the built-in natural ordering of the integers by using the compareTo() method. 1 Comparator<Integer> cmpInt = new Comparator<Integer>(){ 2 public i...
ComputerScienceOne_Page_519_Chunk2055
36. Searching & Sorting 9 return a.getFirstName().compareTo(b.getFirstName()); 10 } else { 11 return a.getLastName().compareTo(b.getLastName()); 12 } 13 } 14 }; 1 /** 2 * This Comparator orders Student objects by 3 * last name/first name in descending (Z-to-A) order 4 */ 5 Comparator<Student> byNameDesc = new Comparato...
ComputerScienceOne_Page_520_Chunk2056
36.2. Searching & Sorting 4 */ 5 Comparator<Student> byGpa = new Comparator<Student>() { 6 @Override 7 public int compare(Student a, Student b) { 8 return b.getGpa().compareTo(a.getGpa()); 9 } 10 }; 36.2. Searching & Sorting We now turn our attention to the search and sorting methods provided by the JDK. Most of these ...
ComputerScienceOne_Page_521_Chunk2057
36. Searching & Sorting public static <T> int binarySearch(T[] a, T key, Comparator<T> c) That is, it takes an array of elements as well as key and a Comparator all of the same type T . It returns an integer representing the index at which it finds the first matching element (there is no guarantee that the first element i...
ComputerScienceOne_Page_522_Chunk2058
36.3. Other Considerations 1 ArrayList<Student> roster = ... 2 3 Student castroKey = null; 4 int castroIndex; 5 6 //create a "key" that will match according to the 7 // Student.equals() method 8 castroKey = new Student("Starlin", "Castro", 131313, 3.95); 9 castroIndex = roster.indexOf(castroKey); 10 System.out.println(...
ComputerScienceOne_Page_523_Chunk2059
36. Searching & Sorting 1 List<Student> roster = ... 2 Student rosterArr[] = ... 3 Comparator byName = ... 4 Comparator byGPA = ... 5 6 //sort by name: 7 Collections.sort(roster, byName); 8 Arrays.sort(rosterArr, byName); 9 10 //sort by GPA: 11 Collections.sort(roster, byGPA); 12 Arrays.sort(rosterArr, byGPA); Code Sam...
ComputerScienceOne_Page_524_Chunk2060
36.3. Other Considerations not. How we handle these is a design decision. We could ignore it, in which case such elements would likely result in a NullPointerException and expect the user to prevent or handle such instances. This may be the preferable choice in most instances, in fact. Alternatively, we could handle nu...
ComputerScienceOne_Page_525_Chunk2061
36. Searching & Sorting also important. To illustrate the importance of these methods, consider the following code. 1 Student a = new Student("Joe", "Smith", 1234, 3.5); 2 Student b = new Student("Joe", "Smith", 1234, 3.5); 3 4 Set<Student> s = new HashSet<Student>(); 5 s.add(a); 6 s.add(b); If we do not override the e...
ComputerScienceOne_Page_526_Chunk2062
36.3. Other Considerations 36.3.4. Java 8: Lambda Expressions Java 8 introduced a lot of functional-style syntax, including lambda expressions. Lambda expressions are essentially anonymous functions that can be passed around to other methods or objects. One use for lambda expressions is if we want to sort a List with r...
ComputerScienceOne_Page_527_Chunk2063
36. Searching & Sorting can be used to modify a Comparator to order null values. 494
ComputerScienceOne_Page_528_Chunk2064
Part III. The PHP Programming Language 495
ComputerScienceOne_Page_529_Chunk2065
37. Basics In the mid-1990s the World Wide Web was in its infancy but becoming more and more popular. For the most part, web pages contained static content: articles and text that was “just-there.” Web pages were far from the fully interactive and dynamic applications that they’ve become. Rasmus Lerdorf had a home page...
ComputerScienceOne_Page_531_Chunk2066
37. Basics 1 <?php 2 3 printf("Hello World\n"); 4 5 ?> Code Sample 37.1.: Hello World Program in PHP 1 <html> 2 <head> 3 <title>Hello World PHP Page</title> 4 </head> 5 <body> 6 <h1>A Simple PHP Script</h1> 7 8 <?php printf("<p>Hello World</p>"); ?> 9 10 </body> 11 </html> Code Sample 37.2.: Hello World Program in PHP ...
ComputerScienceOne_Page_532_Chunk2067
37.2. Basic Elements 37.2. Basic Elements Using the Hello World! program as a starting point, we will examine the basic elements of the PHP language. 37.2.1. Basic Syntax Rules PHP has adopted many aspects of the C programming language (the interpreter itself is written in C). However, there are some major aspects in w...
ComputerScienceOne_Page_533_Chunk2068
37. Basics 37.2.2. PHP Tags PHP code can be interleaved with static HTML or text. Because of this, we need a way to indicate what should be interpreted as PHP and what should be treated as static text. We can do this using PHP tags: the opening tag is <?php and the closing tag is ?> . Anything placed between these tags...
ComputerScienceOne_Page_534_Chunk2069
37.2. Basic Elements Function Description abs($x) Absolute value, |x| ceil($x) Ceiling function, ⌈46.3⌉= 47.0 floor($x) Floor function, ⌊46.3⌋= 46.0 cos($x) Cosine functiona sin($x) Sine functiona tan($x) Tangent functiona exp($x) Exponential function, ex, e = 2.71828 . . . log($x) Natural logarithm, ln (x)b log10($x) ...
ComputerScienceOne_Page_535_Chunk2070
37. Basics slashes is ignored. With a multiline comment, everything in between the forward slash/asterisk is ignored. Comments are ultimately ignored by the interpreter. Consider the following example. 1 //this is a single line comment 2 $x = 10; //this is also a single line comment, but after some code 3 4 /* 5 This i...
ComputerScienceOne_Page_536_Chunk2071
37.3. Variables Internally PHP supports several different types: Booleans, integers, floating point numbers, strings, arrays, and objects. The way that integers are represented may be platform dependent, but are usually 32-bit signed two’s complement integers, able to represent integers between −2, 147, 483, 648 and 2,14...
ComputerScienceOne_Page_537_Chunk2072
37. Basics 1 define("PI", 3.14159); 2 define("INSTITUTION", "University of Nebraska-Lincoln"); 3 define("COST_PER_UNIT", 2.50); Constant names are case sensitive. By convention, we use uppercase underscore casing. An attempt to redefine a constant value will raise a script warning, but will ultimately have no effect. Whe...
ComputerScienceOne_Page_538_Chunk2073
37.4. Operators 1 $x = 10 % 5; //x is 0 2 $x = 10 % 3; //x is 1 3 $x = 29 % 5; //x is 4 37.4.1. Type Juggling The expectations of an arithmetic expression involving two variables that are either integers or floating point numbers are straightforward. We expect the sum/product/etc. as a result. However, since PHP is dyna...
ComputerScienceOne_Page_539_Chunk2074
37. Basics 1 $a = "10"; 2 $b = 5 + $a; //b = 15 3 4 $a = "3.14"; 5 $b = 5 + $a; //b = 8.14 6 7 $a = "ten"; 8 $b = 5 + $a; //b = 5 9 10 //partial conversions also occur: 11 $a = "10ten"; 12 $b = 5 + $a; //b = 15 Code Sample 37.3.: Type Juggling in PHP There are several utility functions that can be used to help determin...
ComputerScienceOne_Page_540_Chunk2075
37.4. Operators Value of $var isset($var) empty($var) is_null($var) 42 bool(true) bool(false) bool(false) "" (an empty string) bool(true) bool(true) bool(false) " " (space) bool(true) bool(false) bool(false) false bool(true) bool(true) bool(false) true bool(true) bool(false) bool(false) array() (an empty array) bool(tr...
ComputerScienceOne_Page_541_Chunk2076
37. Basics 37.4.2. String Concatenation Strings in PHP can be concatenated (combined) in several different ways. One way you can combine strings is by using the concatenation operator. In PHP the string concatenation operator is a single period. 1 $s = "Hello"; 2 $t = "World!"; 3 $msg = $s . " " . $t; //msg contains "He...
ComputerScienceOne_Page_542_Chunk2077
37.6. Examples (short for file get string) using the keyword STDIN (Standard Input). This function will return, as a string, everything the user enters up to and including the enter key (interpreted as the endline character, \n ). To remove the endline character, you can use another function, trim which removes leading...
ComputerScienceOne_Page_543_Chunk2078
37. Basics 6 */ 7 8 //TODO: implement this 9 10 ?> It is common for programmers to use a comment along with a TODO note to themselves as a reminder of things that they still need to do with the program. Let’s first outline the basic steps that our program will go through: 1. We’ll first prompt the user for input, asking ...
ComputerScienceOne_Page_544_Chunk2079
37.6. Examples printf("Please enter degrees in Fahrenheit: "); In the second step, we’ll use the standard input to read the $fahrenheit variable value from the user. Recall that we can use fgets to read from the standard input, but may have to trim the trailing whitespace. $fahrenheit = trim(fgets(STDIN)); If we want t...
ComputerScienceOne_Page_545_Chunk2080
37. Basics 37.6.2. Computing Quadratic Roots Some programs require the user to enter multiple inputs. The prompt-input process can be repeated. In this example, consider asking the user for the coefficients, a, b, c to a quadratic polynomial, ax2 + bx + c and computing its roots using the quadratic formula, x = −b ± √ b2...
ComputerScienceOne_Page_546_Chunk2081
37.6. Examples 1 <?php 2 3 /** 4 * This program computes the roots to a quadratic equation 5 * using the quadratic formula. 6 */ 7 8 printf("Please enter a: "); 9 $a = floatval(trim(fgets(STDIN))); 10 printf("Please enter b: "); 11 $b = floatval(trim(fgets(STDIN))); 12 printf("Please enter c: "); 13 $c = floatval(trim(...
ComputerScienceOne_Page_547_Chunk2082
38. Conditionals PHP supports the basic if, if-else, and if-else-if conditional structures as well as switch statements. Logical statements are built using the standard logical operators for numeric comparisons as well as logical operators such as negations, And, and Or. 38.1. Logical Operators PHP has a built-in Boole...
ComputerScienceOne_Page_549_Chunk2083
38. Conditionals 1 $s = "aardvark"; 2 $t = "zebra"; 3 4 $r = ($s < $t); //true 5 $r = ($s <= $t); //true 6 $r = ($s >= $t); //false 7 $r = ($s > $t); //false However, when these operators are used to compare strings to numeric types, the strings are converted to numbers using the same type juggling that happens when st...
ComputerScienceOne_Page_550_Chunk2084
38.2. If, If-Else, If-Else-If Statements Operator(s) Associativity Notes Highest ++ , -- left-to-right increment operators - , ! right-to-left unary negation operator, logical not * , / , % left-to-right + , - left-to-right addition, subtraction < , <= , > , >= left-to-right comparison == , != , === , !== left-to-right...
ComputerScienceOne_Page_551_Chunk2085
38. Conditionals 1 //example of an if statement: 2 if($x < 10) { 3 printf("x is less than 10\n"); 4 } 5 6 //example of an if-else statement: 7 if($x < 10) { 8 printf("x is less than 10\n"); 9 } else { 10 printf("x is 10 or more \n"); 11 } 12 13 //example of an if-else-if statement: 14 if($x < 10) { 15 printf("x is less...
ComputerScienceOne_Page_552_Chunk2086
38.3. Examples 1 $x = 15; 2 if($x < 10); { 3 printf("x is less than 10\n"); 4 } This PHP code will run without error or warning. However, it will end up printing x is less than 10 , even though x = 15! Recall that a conditional statement binds to the executable statement or code block immediately following it. In this ...
ComputerScienceOne_Page_553_Chunk2087
38. Conditionals formula: logb(x) = loga (x) loga (b) If we can compute some base a, then we can compute any base b. Fortunately we have such a solution. Recall that the standard library provides a function to compute the natural logarithm, log() ). This is one of the fundamentals of problems solving: if a solution alr...
ComputerScienceOne_Page_554_Chunk2088
38.3. Examples 1 //prompt for income from the user 2 printf("Please enter your Adjusted Gross Income: "); 3 4 $income = floatval(trim(fgets(STDIN))); 5 6 //prompt for children 7 printf("How many children do you have? "); 8 $numChildren = intval(trim(fgets(STDIN))); 9 10 if($income < 0 || $numChildren < 0) { 11 printf("...
ComputerScienceOne_Page_555_Chunk2089
38. Conditionals negative). 1 if($baseTax - $credit >= 0) { 2 $totalTax = $baseTax - $credit; 3 } else { 4 $totalTax = 0; 5 } The full program is presented in Code Sample 38.3. 38.3.3. Quadratic Roots Revisited Let’s return to the quadratic roots program we previously designed that uses the quadratic equation to comput...
ComputerScienceOne_Page_556_Chunk2090
38.3. Examples 1 <?php 2 3 /** 4 * This program computes the logarithm base b (b > 1) 5 * of a given number x > 0 6 */ 7 8 if($argc != 3) { 9 printf("Usage: %s b x \n", $argv[0]); 10 exit(1); 11 } 12 13 $b = floatval($argv[1]); 14 $x = floatval($argv[2]); 15 16 if($x <= 0) { 17 printf("Error: x must be greater than zer...
ComputerScienceOne_Page_557_Chunk2091
38. Conditionals 1 <?php 2 //prompt for income from the user 3 printf("Please enter your Adjusted Gross Income: "); 4 5 $income = floatval(trim(fgets(STDIN))); 6 7 //prompt for children 8 printf("How many children do you have? "); 9 $numChildren = intval(trim(fgets(STDIN))); 10 11 if($income < 0 || $numChildren < 0) { ...
ComputerScienceOne_Page_558_Chunk2092
38.3. Examples 1 <?php 2 3 /** 4 * This program computes the roots to a quadratic equation 5 * using the quadratic formula. 6 */ 7 8 if($argc != 4) { 9 printf("Usage: %s a b c\n", $argv[0]); 10 exit(1); 11 } 12 13 $a = floatval($argv[1]); 14 $b = floatval($argv[2]); 15 $c = floatval($argv[3]); 16 17 if($a === 0) { 18 p...
ComputerScienceOne_Page_559_Chunk2093
39. Loops PHP supports while loops, for loops, and do-while loops using the keywords while , for , and do (along with another while ). Continuation conditions for loops are enclosed in parentheses, (...) and blocks of code associated with the loop are enclosed in curly brackets. 39.1. While Loops Code Sample 39.1 conta...
ComputerScienceOne_Page_561_Chunk2094
39. Loops 1 $i = 1; 2 $flag = true; 3 while($flag) { 4 //perform some action 5 $i++; //iteration 6 if($i>10) { 7 $flag = false; 8 } 9 } Code Sample 39.2.: Flag-controlled While Loop in PHP even worse: the program will enter an infinite loop. To see this, the code is essentially equivalent to the following: 1 while($i <=...
ComputerScienceOne_Page_562_Chunk2095
39.3. Do-While Loops 1 $i; 2 for($i=1; $i<=10; $i++) { 3 //perform some action 4 } Code Sample 39.3.: For Loop in PHP 1 $i; 2 do { 3 //perform some action 4 $i++; 5 } while($i <= 10); Code Sample 39.4.: Do-While Loop in PHP 39.3. Do-While Loops PHP also supports do-while loops. Recall that the difference between a while...
ComputerScienceOne_Page_563_Chunk2096
39. Loops 4 } In the foreach syntax we specify the array we want to iterate over, $arr and use the keyword as . The last element in the statement is the variable name that we want to use within the loop. This should be read as “ foreach element $x in the array $arr ...”. Inside the loop, the variable $x will be automat...
ComputerScienceOne_Page_564_Chunk2097
39.5. Examples 1 $sum = 0; 2 for($i=1; $i<=10; $i++) { 3 $sum += $i; 4 } Code Sample 39.6.: Summation of Numbers using a For Loop in PHP 39.5.3. Nested Loops Recall that you can write loops within loops. The inner loop will execute fully for each iteration of the outer loop. An example of two nested of loops in PHP can...
ComputerScienceOne_Page_565_Chunk2098
39. Loops The monthly payment may come out to be a fraction of a cent, say $43.871. For accuracy, we need to ensure that all of the figures for currency are rounded to the nearest cent. The standard math library does have a round() function, but it only rounds to the nearest whole number, not the nearest 100th. However,...
ComputerScienceOne_Page_566_Chunk2099
39.5. Examples 1 <?php 2 if($argc != 4) { 3 printf("Usage: %s principle apr terms\n", $argv[0]); 4 exit(1); 5 } 6 7 $principle = floatval($argv[1]); 8 $apr = floatval($argv[2]); 9 $n = intval($argv[3]); 10 11 $balance = $principle; 12 $monthlyInterestRate = $apr / 12; 13 14 //monthly payment 15 $monthlyPayment = ($mont...
ComputerScienceOne_Page_567_Chunk2100