Introduction to Programming - TXC1, Introduction to Programming - TXC1 Practice

¡Supera tus tareas y exámenes ahora con Quizwiz!

Review 1.01: Explain the difference between using a computer program and programming a computer.

A well-designed computer program is easy to use without any special knowledge. For example, most people can learn to navigate webpages with only a few minutes of practice. On the other hand, programming a computer requires special knowledge about what the computer can fundamentally do and how you would communicate with it through a programming language.

Explain the difference between s = 0; if (x > 0) { s++; } if (y > 0) { s++; } and s = 0; if (x > 0) { s++; } else if (y > 0) { s++; }

In the first block, the conditions are evaluated sequentially, so s could be incremented twice. In the second block, the conditional statements are mutually exclusive, so, s cannot be incremented more than once.

Write a program that prints the product of the first ten positive integers, 1 × 2 × ... × 10. (Use * to indicate multiplication in Java.)

public class PrintProduct { public static void main(String[] args) { System.out.println(1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10); } }

Write a program that prints the sum of the first ten positive integers, 1 + 2 + ... + 10.

public class PrintSum { public static void main(String[] args) { System.out.println(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10); } }

Why is a CD player less flexible than a computer?

A CD player can do one thing—play music CDs. It cannot execute programs.

In which sequence are the lines of the Cubes.java program in Section 5.2 executed, starting with the first line of main?

This is the order in which the lines of code are executed: 8 21 22 9 21 22 10 11

Classify program errors as compile-time and run-time errors.

A compile-time error is a violation of the programming language rules that is detected by the compiler. A run-time error causes a program to take an action that the programmer did not intend.

What is required to play music on a computer?

A program that reads the data on the CD and sends output to the speakers and the screen.

Write a method public static int countVowels(String str) that returns a count of all vowels in the string str. Vowels are the letters a, e, i, o, and u, and their uppercase variants.

/** Count the number of vowels in a given string. @param str string to count vowels in @return number of vowels in str */ public static int countVowels(String str) { int count = 0; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { count++; } } return count; }

Write a method public static int countWords(String str) that returns a count of all words in the string str. Words are separated by spaces. For example, countWords("Mary had a little lamb") should return 5.

/** Count the number of words in a given string. Assume the string is well formed and doesn't have leading or trailing spaces, or multiple spaces in a row. @param str string to count words in @return number of words in str */ public static int countWords(String str) { int count = 1; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch == ' ') { count++; } } return count; }

Write a recursive method public static String reverse(String str) that computes the reverse of a string. For example, reverse("flow") should return "wolf". Hint: Reverse the substring starting at the second character, then add the first character at the end. For example, to reverse "flow", first reverse "low" to "wol", then add the "f" at the end.

/** Reverses a string. @param str input string @return reverse of str */ public static String reverse(String str) { if (str.length() > 1) { return reverse(str.substring(1)) + str.charAt(0); } return str; }

In order to estimate the cost of painting a house, a painter needs to know the surface area of the exterior. Develop an algorithm for computing that value. Your inputs are the width, length, and height of the house, the number of windows and doors, and their dimensions. (Assume the windows and doors have a uniform size.)

// Inputs are width, length, height, number of windows, number of doors, // window width, window height, door width, door height surface area of side 1 = width * height surface area of side 2 = length * height surface area of doors = door width * door height * number of doors surface area of windows = window width * window height * number of windows surface area without doors or windows = (surface area of side 1) * 2 + (surface area of side 2) * 2 // This is what we want to know: total surface area = surface area without doors or windows - (surface area of doors + surface area of windows)

The Two Categories of Errors:

1) Compile-time Errors Syntax Errors Spelling, Capitalization, punctuation Ordering of statements, matching of braces/parenthesis... No .class file is generated by the compiler Correct first error listed, then compile again 2) Run-time Errors Logic Errors Program runs, but produces unintended results Program may 'crash'

Find three run-time errors in the following program. public class HasErrors { public static void main(String[] args) { int x = 0; int y = 0; Scanner in = new Scanner("System.in"); System.out.print("Please enter an integer:"); x = in.readInt(); System.out.print("Please enter another integer: "); x = in.readInt(); System.out.println("The sum is " + x + y); } }

1) The scanner should have been constructed as Scanner in = new Scanner(System.in); 2) The second integer should have been read as y = in.readInt(); 3) The sum should have been printed as "The sum is " + (x + y), so that the integer x is not concatenated with the string "The sum is".

Find at least five compile-time errors in the following program. public class HasErrors { public static void main(); { System.out.print(Please enter two numbers:) x = in.readDouble; y = in.readDouble; System.out.printline("The sum is " + x + y); } }

1) There is an extraneous semicolon after main(). 2) The message in the first print statement is not surrounded by quotation marks like a string should be. 3) The variables x and y are not declared. 4) The variable in is not declared. 5) The method readDouble doesn't exist (nextDouble does). 6) If readDouble were a method, it should be followed by (). 7) In the last line the method println is incorrectly spelled printline.

Variable Names

1. Variable names must start with a letter or the underscore (_) character, and the remaining characters must be letters, numbers, or underscores. (Technically, the $ symbol is allowed as well, but you should not use it—it is intended for names that are automatically generated by tools.) 2. You cannot use other symbols such as ? or %. Spaces are not permitted inside names either. You can use uppercase letters to denote word boundaries, as in cansPerPack. This naming convention is called camel case because the uppercase letters in the middle of the name look like the humps of a camel.) image © GlobalP/iStockphoto 3. Variable names are case sensitive, that is, canVolume and canvolume are different names. 4. You cannot use reserved words such as double or class as names; these words are reserved exclusively for their special Java meanings. (See Appendix C for a listing of all reserved words in Java.)

What is an infinite loop? On your computer, how can you terminate a program that executes an infinite loop?

An infinite loop occurs when the terminating condition in the loop never evaluates to false. How you stop an infinite loop on your computer depends on your operating system and your IDE. For example, in the Eclipse IDE there is a red "TERMINATE" button that will stop any Java program at any time.

Using Dialog Boxes for Input and Output

Call the static showInputDialog method of the JOptionPane class, and supply the string that prompts the input from the user. For example, String input = JOptionPane.showInputDialog("Enter price:"); That method returns a String object. Of course, often you need the input as a number. Use the Integer.parseInt and Double.parseDouble methods to convert the string to a number: double price = Double.parseDouble(input); You can also display output in a dialog box: JOptionPane.showMessageDialog(null, "Price: " + price);

How do you modify the HelloPrinter program to greet you instead?

Change World to your name (here, Dave): System.out.println("Hello, Dave!");

Strings and Characters import java.util.Scanner; /** This program prints a pair of initials. */ public class Initials { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Get the names of the couple System.out.print("Enter your first name: "); String first = in.next(); System.out.print("Enter your significant other's first name: "); String second = in.next(); // Compute and display the inscription String initials = first.substring(0, 1) + "&" + second.substring(0, 1); System.out.println(initials); } } Program Run : Enter your first name: Rodolfo Enter your significant other's first name: Sally R&S

Character literals are delimited by single quotes, and you should not confuse them with strings. • 'H' is a character, a value of type char. • "H" is a string containing a single character, a value of type String. The charAt method returns a char value from a string. The first string position is labeled 0, the second one 1, and so on. H A R R Y 0 1 2 3 4 The position number of the last character (4 for the string "Harry") is always one less than the length of the string. For example, the statement String name = "Harry"; char start = name.charAt(0); char last = name.charAt(4); sets start to the value 'H' and last to the value 'y'.

Describe the building blocks of a simple program.

Classes are the fundamental building blocks of Java programs. Every Java application contains a class with a main method. When the application starts, the instructions in the main method are executed. Each class contains declarations of methods. Each method contains a sequence of instructions. A method is called by specifying the method and its arguments. ring is a sequence of characters enclosed in quotation marks.

Define "computer program" and programming

Computers execute very basic instructions in rapid succession. A computer program is a sequence of instructions and decisions. Programming is the act of designing and implementing computer programs.

Constants

Constants are commonly written using capital letters to distinguish them visually from regular variables: final double BOTTLE_VOLUME = 2;

What do the following statements print? System.out.println("Hello"); System.out.println(""); System.out.println("World");

Hello a blank line World

What does this program print? Pay close attention to spaces. public class Test { public static void main(String[] args) { System.out.print("Hello"); System.out.println("World"); } }

HelloWorld Because there are no spaces after the System.out.print("Hello"); the next line prints World directly after Hello is printed.

Where is a program stored when it is not currently running?

In secondary storage, typically a hard disk.

It is easy to confuse the = and == operators. Write a test program containing the statement if (floor = 13) What error message do you get? Write another test program containing the statement count == 0; What does your compiler do when you compile the program?

In the first case when comparing if (floor = 13) you should get the error "Type mismatch: cannot convert from int to boolean". In the statement count == 0; you should get the error "Syntax error on token "==", invalid assignment operator".

What is the compile-time error in this program? public class Test { public static void main(String[] args) { System.out.println("Hello", "World!"); } }

Java interprets the comma in the println method to mean that two strings are passed to println. It's likely the programmer meant to do this: System.out.print("Hello, World!");

Describe the process of translating high-level languages to machine code.

Java was originally designed for programming consumer devices, but it was first successfully used to write Internet applets. Java was designed to be safe and portable, benefiting both Internet users and students. Java programs are distributed as instructions for a virtual machine, making them platform-independent. Java has a very large library. Focus on learning those parts of the library that you need for your programming projects.

Would the program continue to work if you replaced line 5 with this statement? System.out.println(Hello);

No. The compiler would look for an item whose name is Hello. You need to enclose Hello in quotation marks: System.out.println("Hello");

What does a computer user need to know about programming in order to play a video game?

Nothing.

Write pseudocode for simple algorithms.

Pseudocode is an informal description of a sequence of steps for solving a problem. An algorithm for solving a problem is a sequence of steps that is unambiguous, executable, and terminating.

Write a program that prints a greeting of your choice, perhaps in a language other than English.

Public class Greeting { public static void main(String[] args) { System.out.println("Romanian greeting: Salut! Ce face?"); } }

Write pseudocode for a program that reads a name (such as Harold James Morgan) and then prints a monogram consisting of the initial letters of the first, middle, and last name (such as HJM).

Read first name into variable called first. Read middle name into variable called middle. Read last name into variable called last. Print first character in first. Print first character in middle. Print first character in last.

Write pseudocode for a program that reads a word and then prints the first character, the last character, and the characters in the middle. For example, if the input is Harry, the program prints H y arr.

Read input into a variable called word. Print first character in word followed by a space. Print character at length -1 in word followed by a space. Print substring between 1st and last character (length -1) in word.

What are the two most important benefits of the Java language?

Safety and portability. Other benefit: The same Java program will run, without change, on Windows, UNIX, Linux, or Macintosh.

How would you modify the HelloPrinter program to print the word "Hello" vertically?

System.out.println("H"); System.out.println("e"); System.out.println("l"); System.out.println("l"); System.out.println("o");

Where is the HelloPrinter.java file stored on your computer?

The answer varies among systems. A typical answer might be /home/dave/cs1/hello/HelloPrinter.java or c:\Users\Dave\Workspace\hello\HelloPrinter.java

Describe the components of a computer.

The central processing unit (CPU) performs program control and data processing. Storage devices include memory and secondary storage.

Which part of the computer carries out arithmetic operations, such as addition and multiplication?

The central processing unit.

Write a program that prints the values 3 * 1000 * 1000 * 1000 3.0 * 1000 * 1000 * 1000

This program: public class R222 { public static void main(String[] args) { System.out.println(3 * 1000 * 1000 * 1000); System.out.println(3.0 * 1000 * 1000 * 1000); } } Prints out the following: -1294967296 3.0E9 The reason the first number is negative is because we have exceeded the limited range of an int and the number overflowed to a negative. The second number's result is correct but displayed in scientific notation because it is a floating-point type from the 3.0 in the calculation.

Consider the following code segment. double purchase = 19.93; double payment = 20.00; double change = payment - purchase; System.out.println(change); The code segment prints the change as 0.07000000000000028. Explain why. Give a recommendation to improve the code so that users will not be confused.

The given output is printed in a raw format up to the range of a double data type. Users can use format specifiers (printf with %) to format the output as they require.

What does the following set of statements print? System.out.print("My lucky number is"); System.out.println(3 + 4 + 5);

The printout is My lucky number is12. It would be a good idea to add a space after the is.

What does this program print? public class Test { public static void main(String[] args) { System.out.println("39 + 3"); System.out.println(39 + 3); } }

The program prints the following: 39 + 3 42 Java interprets the statement "39 + 3" as a string and thus prints out the literal characters 39 + 3. Java interprets the second statement 39 + 3 as an operation between two numbers, so it first calculates the value 39 + 3 = 42 then prints out the result 42.

What is the value of mystery after this sequence of statements? int mystery = 1; mystery = 1 - 2 * mystery; mystery = mystery + 1;

The value of mystery is equal to 0 after the statements are executed. In the first statement (line 1), mystery is initialized to a value of 1. In the assignment statement on line 2, mystery is set to -1. Finally, mystery is set to 0 in line 3.

Escape Sequences The sequence \" is called an escape sequence. Another common escape sequence is \n, which denotes a newline character

To include a quotation mark in a literal string, precede it with a backslash (\), like this: "He said \"Hello\"" The backslash is not included in the string. It indicates that the quotation mark that follows should be a part of the string and not mark the end of the string. To include a backslash in a string, use the escape sequence \\, like this: "C:\\Temp\\Secret.txt" Another common escape sequence is \n, which denotes a newline character. Printing a newline character causes the start of a new line on the display. For example, the statement System.out.print("*\n**\n***\n"); prints the characters * ** *** on three separate lines. You often want to add a newline character to the end of the format string when you use System.out.printf: System.out.printf("Price: %10.2f\n", price);

Which parts of a computer can store program code? Which can store user data?

Typically program code is stored on a hard disk, CD/DVD disc, or in some other central location across a network. User data is often more likely to be stored on a local hard disk, although it can also be stored on a network or even a CD/DVD for backup storage.

String Input You can read a string from the console: System.out.print("Please enter your name: "); String name = in.next();

When a string is read with the next method, only one word is read. For example, suppose the user types Harry Morgan as the response to the prompt. This input consists of two words. The call in.next() yields the string "Harry". You can use another call to in.next() to read the second word.

Concatenation

When the expression to the left or the right of a + operator is a string, the other one is automatically forced to become a string as well, and both strings are concatenated. For example, consider this code: String jobTitle = "Agent"; int employeeId = 7; String bond = jobTitle + employeeId;

What do you do to protect yourself from data loss when you work on programming projects?

You back up your files and folders.

How do you get the first character of a string? The last character? How do you remove the first character? The last character?

You can read characters from a string with the charAt method. For the first character, pass a position of 0 to charAt. For the last character pass the position that is equal to the length of the string -1 to charAt. Strings in Java are immutable, so they cannot be directly changed. Thus, to "remove" the first character from a string, we can take a substring of the original string that contains the entire thing minus the first character. If our string is called s, then this works: s.substring(1, s.length());. The last character can be obtained by extracting the substring that contains the entire string minus the last character, like this: s.substring(0, s.length()-1);.

Comments

You use the // delimiter for short comments. If you have a longer comment, enclose it between /* and */ delimiters. The compiler ignores these delimiters and everything in between.

Provide trace tables for these loops. a. int i = 0; int j = 10; int n = 0; while (i j) { i++; j--; n++; } b. int i = 0; int j = 0; int n = 0; while (i 10) { i++; n = n + i + j; j++; } c. int i = 10; int j = 0; int n = 0; while (i > 0) { i--; j++; n = n + i - j; } d. int i = 0; int j = 10; int n = 0; while (i != j) { i = i + 2; j = j - 2; n++; }

a) b) c) d) As the trace table shows, i will never equal j since they pass each other at the 4-6 to 6-4 mark. The trace table stops right below this point to indicate it is an infinite loop.

Write programs that read a line of input as a string and print a. Only the uppercase letters in the string. b. Every second letter of the string. c. The string, with all vowels replaced by an underscore. d. The number of vowels in the string. e. The positions of all vowels in the string.

a) Only the uppercase letters. (Note: Later in the textbook, we will learn how to read a line of text that includes spaces, but for now we are limited to text strings with no spaces, because the Scanner.next method stops reading when it encounters a space.) import java.util.Scanner; public class OnlyUppercaseLetters { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); for (int n = 0; n < word.length(); n++) { // Find out if letter is uppercase or not. char ch = word.charAt(n); if (ch == 'A' || ch == 'B' || ch == 'C' || ch == 'D' || ch == 'E' || ch == 'F' || ch == 'G' || ch == 'H' || ch == 'I' || ch == 'J' || ch == 'K' || ch == 'L' || ch == 'M' || ch == 'N' || ch == 'O' || ch == 'P' || ch == 'Q' || ch == 'R' || ch == 'S' || ch == 'T' || ch == 'U' || ch == 'V' || ch == 'W' || ch == 'X' || ch == 'Y' || ch == 'Z') { System.out.print(ch); } } } } b) Every second letter of the string. import java.util.Scanner; public class SecondLetterString { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); for (int n = 0; n < word.length(); n++) { // Print only if n is odd (which is every second letter) char ch = word.charAt(n); if (n % 2 == 1) // odd { System.out.print(ch); } } } } c) The string with vowels replaced by an underscore. import java.util.Scanner; public class VowelsReplacedUnderscore { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); for (int n = 0; n < word.length(); n++) { // Check each letter to see if a vowel, // and if it is, replace it with an underscore char ch = word.charAt(n); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { System.out.print('_'); } else { System.out.print(ch); } } } } d) The number of vowels in the string. import java.util.Scanner; public class NumberofVowels { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); int numVowels = 0; for (int n = 0; n < word.length(); n++) { // Check each letter to see if a vowel, // and increment counter char ch = word.charAt(n); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { numVowels++; } } System.out.print("Number of vowels: " + numVowels); } } e) The position of the vowels in the string. import java.util.Scanner; public class PositionVowels { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a word with no spaces: "); String word; word = in.next(); System.out.print("Vowels in positions: "); for (int n = 0; n < word.length(); n++) { // Check each letter to see if a vowel, // and print its position char ch = word.charAt(n); if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U') { System.out.print(n + " "); } } } }

Write method headers for methods with the following descriptions. a) Computing the larger of two integers b) Computing the smallest of three floating-point numbers c) Checking whether an integer is a prime number, returning true if it is and false otherwise d) Checking whether a string is contained inside another string e) Computing the balance of an account with a given initial balance, an annual interest rate, and a number of years of earning interest f) Printing the balance of an account with a given initial balance and an annual interest rate over a given number of years g) Printing the calendar for a given month and year h) Computing the weekday for a given day, month, and year (as a string such as "Monday") i) Generating a random integer between 1 and n

a) /** Computes the larger of two integers. @param a first integer @param b second integer @return the larger of a and b */ public static int larger(int a, int b) b) /** Computes the smallest of three floating-point numbers. @param a first number @param b second number @param c third number @return the smallest of a, b, and c */ public static double smallest(double a, double b, double c) c) /** Checks whether an integer is a prime number. @param x number to test @return true if x is prime, otherwise false */ public static boolean isPrime(int x) d) /** Checks to see whether a string is contained inside another string. @param mainString the base string @param possibleInside the string to check to see if it's inside mainString @return true if possibleInside is inside mainString, false otherwise */ public static boolean containedInside(String mainString, String possibleInside) e) /** Computes the balance of an account with a given annual balance, an annual interest rate, and a number of years of earning interest, @param initialBalance initial balance of account @param annualInterestRate the annual interest rate @param numberOfYears number of years earning interest @return the balance of the account after numberOfYears past */ public static double computeBalance(double initialBalance, double annualInterestRate, int numberOfYears) f) /** Prints the balance of an account with a given annual balance, an annual interest rate, and a number of years of earning interest. @param initialBalance initial balance of account @param annualInterestRate the annual interest rate @param numberOfYears number of years earning interest @return the balance of the account after numberOfYears past */ public static void printBalance(double initialBalance, double annualInterestRate, int numberOfYears) g) /** Prints the calendar for a given month and year. @param month numerical value of month @param year numerical value of year */ public static void printCalendar(int month, int year) h) /** Computes the weekday for a given day, month and year. @param day numerical value of day @param month numerical value of month @param year numerical value of year @return the day of the week */ public static String computeWeekDay(int day, int month, int year) i) /** Generates a random integer between 1 and n @param n upper bound of random number @return a random number between 1 and n */ public int generateRandomNumber(int n)

Write a while loop that prints. a. All squares less than n. For example, if n is 100, print 0 1 4 9 16 25 36 49 64 81. b. All positive numbers that are divisible by 10 and less than n. For example, if n is 100, print 10 20 30 40 50 60 70 80 90 c. All powers of two less than n. For example, if n is 100, print 1 2 4 8 16 32 64.

a) int i = 0; while (i * i < n) { System.out.println(i * i); i++; } b) int i = 10; while (i < n) { System.out.println(i); i = i + 10; } c) int i = 1; while (i < n) { System.out.println(i); i = i * 2; }

Write a loop that computes a. The sum of all even numbers between 2 and 100 (inclusive). b. The sum of all squares between 1 and 100 (inclusive). c. The sum of all odd numbers between a and b (inclusive). d. The sum of all odd digits of n. (For example, if n is 32677, the sum would be 3 + 7 + 7 = 17.)

a) int sumOfEvenNumbers = 0; for (int n <= 2; n = 100; n = n + 2) { sumOfEvenNumbers = sumOfEvenNumbers + n; } // sumOfEvenNumbers now has the sum of all even numbers from 2 to 100 b) int sumOfSquares = 0; int currentN = 1; while (Math.pow(currentN, 2) <= 100) { sumOfSquares = sumOfSquares + Math.pow(currentN, 2); currentN++; } // sumOfSquares now has the sum of all squares from 1 to 100 c) int sumOfOddNumbers = 0; for (int n = a; n <= b; n++) { if (n % 2 == 1) { sumOfOddNumbers = sumOfOddNumbers + n; } } //sumOfOddNumbers now has the value of all odd numbers between a and b d) int nLeft = n; int sumOfOddDigits = 0; while (nLeft > 0) { int digit = nLeft % 10; if (digit % 2 == 1) { sumOfOddDigits = sumOfOddDigits + digit; } nLeft = nLeft / 10; } // sumOfOddNumbers now has sum of all odd digits in n

Write the following methods and provide a program to test them. a) double smallest(double x, double y, double z), returning the smallest of the arguments b) double average(double x, double y, double z), returning the average of the arguments

a) public double smallest(double x, double y, double z), returning the smallest of the arguments import java.util.Scanner; public class Smallest { /** Returns the smallest of the three arguments. @param x the first number @param y the second number @param z the third number @return a double which is the smallest of the three params */ public static double smallest(double x, double y, double z) { if (x <= y && x <= z) { return x; } else if (y <= x && y <= z) { return y; } else { return z; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); System.out.println("The smallest number is: " + smallest(a, b, c)); } } b) public double average(double x, double y, double z), returning the average of the arguments import java.util.Scanner; public class Average { /** Returns the average of the three arguments. @param x the first number @param y the second number @param z the third number @return a double which is the average of the three */ public static double average(double x, double y, double z) { return (x + y + z) / 3.0; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); System.out.println("The average of the numbers is: " + average(a, b, c)); } }

What do these loops print? a. for (int i = 1; i 10; i++) { System.out.print(i + " "); } b. for (int i = 1; i 10; i += 2) { System.out.print(i + " "); } c. for (int i = 10; i > 1; i--) { System.out.print(i + " "); } d. for (int i = 0; i 10; i++) { System.out.print(i + " "); } e. for (int i = 1; i 10; i = i * 2) { System.out.print(i + " "); } f. for (int i = 1; i 10; i++) { if (i % 2 == 0) { System.out.print(i + " "); } }

a) 1 2 3 4 5 6 7 8 9 b) 1 3 5 7 9 c) 10 9 8 7 6 5 4 3 2 d) 0 1 2 3 4 5 6 7 8 9 e) 1 2 4 8 f) 2 4 6 8

What are the values of the following expressions? In each line, assume that double x = 2.5; double y = -1.5; int m = 18; int n = 4; a) x + n * y - (x + n) * y b) m / n + m % n c) 5 * x - n / 5 d) 1 - (1 - (1 - (1 - (1 - n)))) e) Math.sqrt(Math.sqrt(n))

a) 6.25 b) 6 c) 12.5 d) -3 e) 1.4142135623730951

True or false? a) A method has exactly one return statement. b) A method has at least one return statement. c) A method has at most one return value. d) A method with return value void never has a return statement. e) When executing a return statement, the method exits immediately. f) A method with return value void must print a result. g) A method without parameter variables always returns the same value.

a) False b) False c) True d) False e) True f) False g) False

Give examples of the following methods from the Java library. a) A method with a double argument and a double return value b) A method with two double arguments and a double return value c) A method with a String argument and a double return value d) A method with no arguments and a double return value

a) Math.sqrt(x) b) Math.pow(x, y) c) Double.parseDouble(x) d) Math.random()

Write programs that read a sequence of integer inputs and print a. The smallest and largest of the inputs. b. The number of even and odd inputs. c. Cumulative totals. For example, if the input is 1 7 2 9, the program should print 1 8 10 19. d. All adjacent duplicates. For example, if the input is 1 3 3 4 5 5 6 6 2, the program should print 3 5 6.

a) Smallest and largest of the inputs import java.util.Scanner; public class LargestInput { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a series of numbers, then type Q to process: "); int largest; largest = in.nextInt(); int smallest = largest; int input; // Loop on input and check for a new min or max while (in.hasNextInt()) { input = in.nextInt(); if (input > largest) { largest = input; } if (input < smallest) { smallest = input; } } // Output the results System.out.print("Largest: " + largest + "\n" + "Smallest: " + smallest); } } b) Number of even and odd inputs import java.util.Scanner; public class NumberEvenOddInputs { public static void main(String[] args) { int numOdd = 0; int numEven = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a series of numbers, then type Q to process: "); int input; // Loop on input and check oddness or evenness while (in.hasNextInt()) { input = in.nextInt(); if (input % 2 == 0) // even { numEven++; } else // odd { numOdd++; } } // Print the results System.out.println("Number of even: " + numEven + "\n" + "Number of odd: " + numOdd); } } c) Cumulative totals import java.util.Scanner; public class CummulativeTotals { public static void main(String[] args) { double sum = 0.0; Scanner in = new Scanner(System.in); System.out.print("Enter a series of numbers, then type Q to process: "); double input; // Calculate and print cumulative totals while (in.hasNextDouble()) { input = in.nextDouble(); sum = sum + input; System.out.print(sum + " "); } } } d) All adjacent duplicates import java.util.Scanner; public class AdjacentDuplicates { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print( "Enter a series of numbers, then type Q to process: "); int input; int previous; previous = in.nextInt(); // Find and print adjacent duplicates while (in.hasNextInt()) { input = in.nextInt(); if (input == previous) { System.out.print(input + " "); } previous = input; } } }

Write programs with loops that compute a. The sum of all even numbers between 2 and 100 (inclusive). b. The sum of all squares between 1 and 100 (inclusive). c. All powers of 2 from 20 up to 220. d. The sum of all odd numbers between a and b (inclusive), where a and b are inputs. e. The sum of all odd digits of an input. (For example, if the input is 32677, the sum would be 3 + 7 + 7 = 17.)

a) Sum of all even numbers between 2 and 100 public class SumEvenNumbers { public static void main(String[] args) { int sum = 0; // The sum of all even numbers between 2 and 100 for (int x = 2; x <= 100; x = x + 2) { sum = sum + x; } // Output the result System.out.println("The sum is " + sum); } } b) Sum of all squares between 1 and 100 public class SumSquares { public static void main(String[] args) { int sum = 0; // The sum of all squares between 1 and 100 for (int x = 1; x <= 100; x++) { sum = sum + x * x; } // Output the result System.out.println("The sum is " + sum); } } c) The powers of 2 from 20 up to 220 public class Powerof2 { public static void main(String[] args) { // The powers of 2 from 2^0 to 2^20 for (int x = 0; x <= 20; x++) { System.out.println( "2 to the " + x + " equals " + Math.pow(2.0, x)); } } } d) Sum of all odd numbers between a and b (which are inputs) import java.util.Scanner; public class SumOfOddNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Get the inputs System.out.print("Enter a: "); int a; a = in.nextInt(); System.out.print("Enter b: "); int b; b = in.nextInt(); int sum = 0; // The sum of odd numbers between a and b for (int x = a; x <= b; x++) { // Only add number if it is odd if (x % 2 == 1) { sum = sum + x; } } // Output the result System.out.println("The sum is " + sum + "."); } e) Sum of all odd digits of an input import java.util.Scanner; public class SumOfOddDigits { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Get the input System.out.print("Enter an integer number: "); int num; num = in.nextInt(); int sum = 0; int digit; // The sum of odd digits of the input while (num > 0) { digit = num % 10; // Only add digit if it is odd if (digit % 2 == 1) { sum = sum + digit; } num = num / 10; } // Output the result System.out.print("The sum is " + sum + "."); } }

Write a program that prints a multiplication table, like this:

public class PrintMultiplicationTable { public static void main(String[] args) { int maxDigit = 10; for (int i = 1; i <= maxDigit; i++) { for (int j = 1; j <= maxDigit; j++) { System.out.printf("%4d", i * j); } System.out.println(); } } }

Find the errors in the following if statements. a) if x > 0 then System.out.print(x); b) if (1 + x > Math.pow(x, Math.sqrt(2)) { y = y + x; } c) if (x = 1) { y++; } d) x = in.nextInt(); if (in.hasNextInt()) { sum = sum + x; } else { System.out.println("Bad input for x"); } e) String letterGrade = "F"; if (grade >= 90) { letterGrade = "A"; } if (grade >= 80) { letterGrade = "B"; } if (grade >= 70) { letterGrade = "C"; } if (grade >= 60) { letterGrade = "D"; }

a) There are two errors in this code. First, there are no parentheses around the x > 0 part of the if statement. Secondly, there is an extraneous then which is not part of the Java syntax, instead we should wrap the body of the if statement in curly braces. A correct form would be: if (x > 0) { System.out.print(x); } b) In this statement there aren't enough parentheses to balance the condition (there are only two). The following would be correct: if (1 + x > Math.pow(x, Math.sqrt(2))) { y = y + x; } c) In this case there is only a single = in the if statement. Likely the programmer wanted to check for equality rather than set x equal to the value of 1. A correct form would be: if (x == 1) { y++; } d) The problem in this case is that the programmer tried to validate the input after she read it thus defeating the whole purpose of input validation. Instead we should take the line which reads the integer into the body of the if statement, like this: if (in.hasNextInt()) { x = in.nextInt(); sum = sum + x; } else { System.out.println("Bad input for x"); e) The if statements should be an if/else if/else sequence. More than one if statement will be executed for any grade higher than 60 and the letter grade will be wrongly assigned.

Explain what each of the following program segments computes. a) x = 2; y = x + x; b) s = "2"; t = s + s;

a) This statement doubles the value of x. Given the initial value of x as 2, the result is 4. b) This statement concatenates the strings "2" together. The result is "22".

What is the value of each variable after the if statement? a) int n = 1; int k = 2; int r = n; if (k < n) { r = k; } b) int n = 1; int k = 2; int r; if (n < k) { r = k; } else { r = k + n; } c) int n = 1; int k = 2; int r = k; if (r < k) { n = r; } else { k = n; } d) int n = 1; int k = 2; int r = 3; if (r < n + k) { r = 2 * n; } else { k = 2 * r; }

a) n = 1, k = 2, r = 1 b) n = 1, k = 2, r = 2 c) n = 1, k = 1, r = 2 d) n = 1, k = 6, r = 3

Write an algorithm to settle the following question: A bank account starts out with $10,000. Interest is compounded monthly at 6 percent per year (0.5 percent per month). Every month, $500 is withdrawn to meet college expenses. After how many years is the account depleted?

balance = $10,000 total months = 0 while balance is greater than $0 increase balance by 0.5% of its value decrease balance by $500 add 1 to the total number of months years to deplete = total months / 12

The following algorithm yields the season (Spring, Summer, Fall, or Winter) for a given month and day. If month is 1, 2, or 3, season = "Winter" Else if month is 4, 5, or 6, season = "Spring" Else if month is 7, 8, or 9, season = "Summer" Else if month is 10, 11, or 12, season = "Fall" If month is divisible by 3 and day >= 21 If season is "Winter", season = "Spring" Else if season is "Spring", season = "Summer" Else if season is "Summer", season = "Fall" Else season = "Winter" Write a program that prompts the user for a month and day and then prints the season, as determined by this algorithm.

import java.util.Scanner; public class Season { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a month and day: "); int month = in.nextInt(); int day = in.nextInt(); String season = ""; if (month <= 3) { season = "Winter"; } else if (month <= 6) { season = "Spring"; } else if (month <= 9) { season = "Summer"; } else { season = "Fall"; } if (month % 3 == 0 && day >= 21) { if (season.compareTo("Winter") == 0) { season = "Spring"; } else if (season.compareTo("Spring") == 0) { season = "Summer"; } else if (season.compareTo("Summer") == 0) { season = "Fall"; } else { season = "Winter"; } } System.out.println(season); } }

Write a program that prompts the user for a measurement in meters and then converts it to miles, feet, and inches.

import java.util.Scanner; public class ConvertMeasurements { public static void main(String[] args) { final double METERS_PER_MILE = 1609.344; final double METERS_PER_FEET = 0.3048; final double METERS_PER_INCH = 0.0254; Scanner in = new Scanner(System.in); System.out.print("Please enter a measurement in meters: "); double meters = in.nextDouble(); System.out.println("Coverted to miles: " + meters / METERS_PER_MILE); System.out.println("Coverted to feet: " + meters / METERS_PER_FEET); System.out.println("Coverted to inches: " + meters / METERS_PER_INCH); } }

Write the following methods and provide a program to test them. a) boolean allTheSame(double x, double y, double z), returning true if the arguments are all the same b) boolean allDifferent(double x, double y, double z), returning true if the arguments are all different c) boolean sorted(double x, double y, double z), returning true if the arguments are sorted, with the smallest one coming first

import java.util.Scanner; public class BoolTest { /** Determines if the three arguments are all equal. @param x the first number @param y the second number @param z the third number @return true if all the same, otherwise false */ public static boolean allTheSame(double x, double y, double z) { if (x == y && y == z) { return true; } else { return false; } } /** Determines if the three arguments are all NOT equal. @param x the first number @param y the second number @param z the third number @return true if all different, otherwise false */ public static boolean allDifferent(double x, double y, double z) { if (x != y && y != z && x != z) { return true; } else { return false; } } /** Determines if the three arguments are in order, smallest first. @param x the first number @param y the second number @param z the third number @return true if in order, otherwise false */ public static boolean sorted(double x, double y, double z) { if (x <= y && y <= z) { return true; } else { return false; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); if (allTheSame(a, b, c)) { System.out.println("All the same!"); } if (allDifferent(a, b, c)) { System.out.println("All different!"); } if (sorted(a, b, c)) { System.out.println("Those darned numbers are sorted!"); } } }

The original U.S. income tax of 1913 was quite simple. The tax was • 1 percent on the first $50,000. • 2 percent on the amount over $50,000 up to $75,000. • 3 percent on the amount over $75,000 up to $100,000. • 4 percent on the amount over $100,000 up to $250,000. • 5 percent on the amount over $250,000 up to $500,000. • 6 percent on the amount over $500,000. There was no separate schedule for single or married taxpayers. Write a program that computes the income tax according to this schedule.

import java.util.Scanner; public class Calculate1913Tax { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter your income:"); double income = in.nextDouble(); final double PERCENT_PER_STEP = 0.01; double tax = income * PERCENT_PER_STEP; if (income > 50000) { tax += (income-50000) * PERCENT_PER_STEP; } if (income > 75000) { tax += (income - 75000) * PERCENT_PER_STEP; } if (income > 100000) { tax += (income - 100000) * PERCENT_PER_STEP; } if (income > 250000) { tax += (income - 250000) * PERCENT_PER_STEP; } if (income > 500000) { tax += (income - 500000) * PERCENT_PER_STEP; } System.out.printf("You owe $%.2f in tax.\n", tax); } }

Complete the program in How To 4.1. Your program should read twelve temperature values and print the month with the highest temperature.

import java.util.Scanner; public class HottestMonth { public static void main(String[] args) { Scanner in = new Scanner(System.in); double highestValue; highestValue = in.nextDouble(); int highestMonth = 1; for (int currentMonth = 2; currentMonth<= 12; currentMonth++) { double nextValue = in.nextDouble(); if (nextValue > highestValue) { highestValue = nextValue; highestMonth = currentMonth; } } System.out.println(highestMonth); } }

Write a program that translates a letter grade into a number grade. Letter grades are A, B, C, D, and F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and 0. There is no F+ or F-. A + increases the numeric value by 0.3, a - decreases it by 0.3. However, an A+ has value 4.0.

import java.util.Scanner; public class LetterGradeToNumber { public static void main(String[] args) { Scanner in = new Scanner(System.in); final double A_VALUE = 4.0; final double B_VALUE = 3.0; final double C_VALUE = 2.0; final double D_VALUE = 1.0; final double F_VALUE = 0.0; final double PLUS_OR_MINUS_ADJUSTMENT = 0.3; System.out.println("Enter letter grade: "); String grade = in.next(); double numericValue = F_VALUE; if (grade.charAt(0) == 'A') { numericValue = A_VALUE; } if (grade.charAt(0) == 'B') { numericValue = B_VALUE; } if (grade.charAt(0) == 'C') { numericValue = C_VALUE; } if (grade.charAt(0) == 'D') { numericValue = D_VALUE; } if (grade.charAt(0) == 'F') { numericValue = F_VALUE; } if (grade.length() == 2) { // has a + or - if (grade.charAt(1) == '+') { if (grade.charAt(0) != 'A') { numericValue += PLUS_OR_MINUS_ADJUSTMENT; } } else { // It must be a '-' numericValue -= PLUS_OR_MINUS_ADJUSTMENT; } } System.out.printf("The numeric value is %.1f.", numericValue); } }

Write a program that reads a temperature value and the letter C for Celsius or F for Fahrenheit. Print whether water is liquid, solid, or gaseous at the given temperature at sea level.

import java.util.Scanner; public class MatterState { public static void main(String[] args) { final double GAS_STATE_CELSIUS = 100; final double LIQUID_STATE_CELSIUS = 0; final double GAS_STATE_FAHRENHEIT = 212; final double LIQUID_STATE_FAHRENHEIT = 32; Scanner in = new Scanner(System.in); System.out.println("Enter temperature: "); double temp = in.nextDouble(); System.out.println("Enter C for Celsius or F for Fahrenheit:"); String type = in.next(); if (type.compareTo("C") == 0) { // Celsius if (temp > GAS_STATE_CELSIUS) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_CELSIUS) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } else { // Fahrenheit if (temp > GAS_STATE_FAHRENHEIT) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_FAHRENHEIT) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } } }

The boiling point of water drops by about one degree centigrade for every 300 meters (or 1,000 feet) of altitude. Improve the program of Exercise R3.9 to allow the user to supply the altitude in meters or feet.

import java.util.Scanner; public class MatterState { public static void main(String[] args) { final double GAS_STATE_CELSIUS = 100; final double LIQUID_STATE_CELSIUS = 0; final double GAS_STATE_FAHRENHEIT = 212; final double LIQUID_STATE_FAHRENHEIT = 32; final double BOILING_POINT_DROP_CELSIUS_FEET = 1000; final double BOILING_POINT_DROP_CELSIUS_METERS = 300; final double BOILING_POINT_DROP_FAHRENHEIT_FEET = 5.0 / 9.0 * BOILING_POINT_DROP_CELSIUS_FEET; final double BOILING_POINT_DROP_FAHRENHEIT_METERS = 5.0 / 9.0 * BOILING_POINT_DROP_CELSIUS_METERS; Scanner in = new Scanner(System.in); System.out.println("Enter temperature: "); double temp = in.nextDouble(); System.out.println("Enter C for Celsius or F for Fahrenheit:"); String type = in.next(); System.out.println("Enter elevation: "); double elevation = in.nextDouble(); System.out.println("Enter M for meters or F for feet: "); String elevationUnits = in.next(); if (type.compareTo("C") == 0) { double boilingPoint = GAS_STATE_CELSIUS; if (elevationUnits.compareTo("F") == 0) { boilingPoint -= BOILING_POINT_DROP_CELSIUS_FEET * elevation; } else { boilingPoint -= BOILING_POINT_DROP_CELSIUS_METERS * elevation; } // Celsius if (temp > boilingPoint) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_CELSIUS) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } else { double boilingPoint = GAS_STATE_FAHRENHEIT; if (elevationUnits.compareTo("F") == 0) { boilingPoint -= BOILING_POINT_DROP_FAHRENHEIT_FEET * elevation; } else { boilingPoint -= BOILING_POINT_DROP_FAHRENHEIT_METERS * elevation; } // Fahrenheit if (temp > boilingPoint) { System.out.println("It's a gas."); } else if (temp > LIQUID_STATE_FAHRENHEIT) { System.out.println("It's a liquid."); } else { System.out.println("It's a solid."); } } } }

Write a program that transforms numbers 1, 2, 3, ..., 12 into the corresponding month names January, February, March, ..., December. Hint: Make a very long string "January February March ...", in which you add spaces such that each month name has the same length. Then use substring to extract the month you want.

import java.util.Scanner; public class MonthNames { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a month number (1 through 12): "); int month = in.nextInt(); String monthNames = "January February March April May June" + " July August September October November December "; String monthAsText = monthNames.substring((month - 1) * 9, (month) * 9); System.out.println(monthAsText); } }

An online bank wants you to create a program that shows prospective customers how their deposits will grow. Your program should read the initial balance and the annual interest rate. Interest is compounded monthly. Print out the balances after the first three months.

import java.util.Scanner; public class MonthlyBalance { public static void main(String[] args) { Scanner in = new Scanner(System.in); // input of balance and rate System.out.print("Initial balance : "); double initAmt = in.nextDouble(); System.out.print("Annual interest rate in percent: "); double rate = in.nextDouble(); // formatted output initAmt = initAmt + initAmt * (rate /(100.0*12)); System.out.printf("After first month: %.2f\n ", initAmt); initAmt = initAmt + initAmt * (rate /(100.0*12)); System.out.printf("After second month: %.2f\n" , initAmt); initAmt = initAmt + initAmt * (rate /(100.0*12)); System.out.printf("After third month: %.2f\n" , initAmt); } }

Write a program that reads three numbers and prints "all the same" if they are all the same, "all different" if they are all different, and "neither" otherwise.

import java.util.Scanner; public class NumCompare { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter three numbers: "); double a = in.nextDouble(); double b = in.nextDouble(); double c = in.nextDouble(); if (a == b && b == c) { System.out.println("all the same"); } else if (a != b && b != c && c != a) { System.out.println("all different"); } else { System.out.println("neither"); } } }

Write a program that reads an integer and prints whether it is negative, zero, or positive.

import java.util.Scanner; public class NumberInt { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a number: "); int i = in.nextInt(); if (i < 0) { System.out.println("It's a negative number."); } else if (i == 0) { System.out.println("It's a zero."); } else { System.out.println("It's a positive number."); } } }

Write a program that reads a word and prints all substrings, sorted by length. For example, if the user provides the input "rum", the program prints

import java.util.Scanner; public class PrintAllSubstrings { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a word: "); String word = in.next(); for (int length = 1; length <= word.length(); length++) { // This loop boundary defines the last position we can reach without // going off the end of the string for (int pos = 0; pos <= word.length() - length; pos++) { System.out.println(word.substring(pos, pos + length)); } } } }

Write a program that prompts the user for two integers and then prints • The sum • The difference • The product • The average • The distance (absolute value of the difference) • The maximum (the larger of the two) • The minimum (the smaller of the two) Hint: The max and min functions are declared in the Math class.

import java.util.Scanner; public class PrintNumberStats { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter the first integer: "); int firstInt = in.nextInt(); System.out.print("Please enter the second integer: "); int secondInt = in.nextInt(); int sum = firstInt + secondInt; System.out.printf("Sum: %d\n", sum); int difference = firstInt - secondInt; System.out.printf("Difference: %d\n", difference); int product = firstInt * secondInt; System.out.printf("Product: %d\n", product); double average = (firstInt + secondInt) / 2.0; System.out.printf("Average: %f\n", average); int distance = Math.abs(difference); System.out.printf("Distance: %d\n", distance); int max = Math.max(firstInt, secondInt); System.out.printf("Maximum: %d\n", max); int min = Math.min(firstInt, secondInt); System.out.printf("Minimum: %d\n", min); } }

Write a program that prompts the user for a radius and then prints • The area and circumference of a circle with that radius • The volume and surface area of a sphere with that radius

import java.util.Scanner; public class RadiusCalculations { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a radius: "); double radius = in.nextDouble(); System.out.println("Area of circle:" + (Math.PI * Math.pow(radius, 2))); System.out.println("Circumference of circle: " + (2 * Math.PI * radius)); System.out.println("Volume of sphere: " + (4.0 / 3.0 * Math.PI * Math.pow(radius, 3))); System.out.println("Surface area of sphere: " + (4.0 * Math.PI * Math.pow(radius, 2))); } }

Write a program that reads a word and prints the word in reverse. For example, if the user provides the input "Harry", the program prints yrraH

import java.util.Scanner; public class ReverseWord { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter a word: "); String word = in.next(); for (int i = word.length() - 1; i >= 0; i--) { System.out.print(word.charAt(i)); } } }

Write a program that reads in two floating-point numbers and tests whether they are the same up to two decimal places. Here are two sample runs.

import java.util.Scanner; public class SameToTwoDecimalPlaces { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter two floating point numbers: "); double x = in.nextDouble(); double y = in.nextDouble(); if (Math.abs(x - y) < 0.01) { System.out.println("They are the same up to two decimal places."); } else { System.out.println("They are different."); } } }

Write a program that reads a number and displays the square, cube, and fourth power. Use the Math.pow method only for the fourth power.

import java.util.Scanner; public class Powers { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); double number = in.nextDouble(); double square = number * number; System.out.printf("Square: %f\n", square); double cube = number * number * number; System.out.printf("Cube: %f\n", cube); double fourthPower = Math.pow(number, 4); System.out.printf("Fourth Power: %f\n", fourthPower); } }

Number Types

int - The integer type, with range −2,147,483,648 (Integer.MIN_VALUE) ... 2,147,483,647 (Integer.MAX_VALUE, about 2.14 billion) 4 bytes byte - The type describing a single byte consisting of 8 bits, with range −128 ... 127 - 1 byte short - The short integer type, with range −32,768 ... 32,767 2 bytes long - The long integer type, with about 19 decimal digits 8 bytes double - The double-precision floating-point type, with about 15 decimal digits and a range of about ±10308 8 bytes float - The single-precision floating-point type, with about 7 decimal digits and a range of about ±1038 - 4 bytes char - The character type, representing code units in the Unicode encoding scheme (see Random Fact 2.2) - 2 bytes

Rewrite the following do loop into a while loop. int n = in.nextInt(); double x = 0; double s; do { s = 1.0 / (1 + n * n); n++; x = x + s; } while (s > 0.01);

int n = in.nextInt(); double x = 0; double s; s = 1.0 / (1 + n * n); n++; x = x + s; while (s > 0.01) { s = 1.0 / (1 + n * n); n++; x = x + s; }

Rewrite the following for loop into a while loop. int s = 0; for (int i = 1; i = 10; i++) { s = s + i; }

int s = 0; int i = 1; while (i <= 10) { s = s + i; i++; }

Each square on a chess board can be described by a letter and number, such as g5 in this example: The following pseudocode describes an algorithm that determines whether a square with a given letter and number is dark (black) or light (white). If the letter is an a, c, e, or g If the number is odd color = "black" Else color = "white" Else If the number is even color = "black" Else color = "white" Using the procedure in Programming Tip 3.5, trace this pseudocode with input g5.

letter number color 9 5 "black"

Write a program that prints the balance of an account after the first, second, and third year. The account has an initial balance of $1,000 and earns 5 percent interest per year.

public class AccountBalance{ public static void main(String[] args) { System.out.println(1000 * 1.05); System.out.println(1000 * 1.05 * 1.05); System.out.println(1000 * 1.05 * 1.05 * 1.05); } }

rite a program that displays the dimensions of a letter-size (8.5 × 11 inches) sheet of paper in millimeters. There are 25.4 millimeters per inch. Use constants and comments in your program.

public class LetterDim { public static void main(String[] args) { // Define a constant for the conversion to metric final double INCHES_TO_MILLIMETERS = 25.4; // Define constants for paper size in inches final double PAPER_WIDTH_IN = 8.5; final double PAPER_LENGTH_IN = 11.0; // Define variables for millimeters and convert double paperWidthmm = PAPER_WIDTH_IN * INCHES_TO_MILLIMETERS; double paperLengthmm = PAPER_LENGTH_IN * INCHES_TO_MILLIMETERS; // Display (print to screen) the dimensions in mm System.out.println("The metric dimensions of a letter-sized sheet of paper are " + paperWidthmm+ " mm by " + paperLengthmm + " mm."); } }

Write a program that displays your name inside a box on the screen, like this: Do your best to approximate lines with characters such as | - +.

public class NameInABox { public static void main(String[] args) { System.out.println("+------+"); System.out.println("| Dave |"); System.out.println("+------+"); } }

Printing a grid. Write a program that prints the following grid to play tic-tac-toe. Of course, you could simply write seven statements of the form System.out.println("+--+--+--+"); You should do it the smart way, though. Declare string variables to hold two kinds of patterns: a comb-shaped pattern and the bottom line. Print the comb three times and the bottom line once.

public class PrintGrid { public static void main(String[] args) { String bottomLine = "+--+--+--+"; String combPattern = "+--+--+--+\n| | | |"; System.out.println(combPattern); System.out.println(combPattern); System.out.println(combPattern); System.out.println(bottomLine); } }

Declare variables with appropriate names and types.

• A variable is a storage location with a name. • When declaring a variable, you usually specify an initial value. • When declaring a variable, you also specify the type of its values. • Use the int type for numbers that cannot have a fractional part. • Use the double type for floating-point numbers. • By convention, variable names should start with a lowercase letter. • An assignment statement stores a new value in a variable, replacing the previously stored value. • The assignment operator = does not denote mathematical equality. • You cannot change the value of a variable that is defined as final. • Use comments to add explanations for humans who read your code. The compiler ignores comments.

Write programs that read user input and print formatted output.

• Java classes are grouped into packages. Use the import statement to use classes from packages. • Use the Scanner class to read keyboard input in a console window. • Use the printf method to specify how values should be Formated • The API (Application Programming Interface) documentation lists the classes and methods of the Java library.

Write arithmetic expressions in Java.

• Mixing integers and floating-point values in an arithmetic expression yields a floating-point value. • The ++ operator adds 1 to a variable; the −− operator subtracts 1. • If both arguments of / are integers, the remainder is discarded. • The % operator computes the remainder of an integer division. • The Java library declares many mathematical functions, such as Math.sqrt (square root) and Math.pow (raising to a power). • You use a cast (typeName) to convert a value to a different type.

Write programs that process strings.

• Strings are sequences of characters. • The length method yields the number of characters in a string. • Use the + operator to concatenate strings; that is, to put them together to yield a longer string. • Whenever one of the arguments of the + operator is a string, the other argument is converted to a string. • Use the next method of the Scanner class to read a string containing a single word. • String positions are counted starting with 0. • Use the substring method to extract a part of a string.

This chapter contains a number of recommendations regarding variables and constants that make programs easier to read and maintain. Briefly summarize these recommendations.

• Variable names are in lowercase with occasional uppercase characters in the middle. • Constant names are in uppercase with the occasional underscore. • No magic numbers may be used.


Conjuntos de estudio relacionados

Test Bank- Electrolytes and Fluid Balance

View Set

Ch. 7 Nursing Process and Standard of Care

View Set

NCLEX questions: Perioperative Nursing

View Set

EXAM 2 Practice Questions - CH 28

View Set

Child Health - Infectious & Communicable Disease

View Set

World History Chapter 13 True/False

View Set

CH 32: Hematologic function and treatment modalities

View Set