calculateSemesterAverage
is more meaningful than
looking at a sequence of statements that actually performs the calculation
Write a program that prompts the user for a double and uses the round
method of the Math
class
to print the integer resulting from rounding the double.
import java.util.*; import java.io.*; public class Rounder { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(System.in); System.out.print("Enter a double: "); double d = scanner.nextDouble(); System.out.println(d + " rounds to " + Math.round(d)); } }
Here is a sample execution of the program. User input is in bold.
Enter a double: 23.1 23.1 rounds to 23
Write a program that finds prompts the user for the side of a square and prints the length of the diagonal.
import java.util.*; public class Pythagoras { public static void main(String [] args) throws Exception { Scanner scanner = new Scanner(System.in); System.out.print("Enter the (integer) length of the side of the square: "); int side = scanner.nextInt(); double diagonal = Math.sqrt(2) * side; System.out.println("The length of the diagonal of a square with a side of length " + side + " is " + diagonal); } }
Here is a sample execution of the program. User input is in bold. Enter the (integer) length of the side of the square: 1 The length of the diagonal of a square with a side of length 1 is 1.4142135623730951
Math.abs(i)
Math.round(d)
Math.sqrt(d)
scanner.nextInt()
Scanner
objects until now were all based on the keyboard; i.e., the input comes from the keyboard. We will soon see
that input can come from other places as well … in particular files on disk. When creating a Scanner
object,
one specifies where the input should come from; that is then maintained within the particular created object (e.g. scanner
).
Thus when calling nextInt
on an object created from the keyboard, the input will come from the keyboard; from a file, the
input will come from a file.
Redo HelloWorld
using a method for the display of Hello world
Codeclass HelloWorld { public static void main(String [] args) { displayHelloWorld(); } public static void displayHelloWorld() { System.out.println("Hello world"); } }
At the very least, a method definition consists of
displayHelloWorld
)
main
(which is a method), we will require the public static
boilerplate
{}
's following the method header)
println()
, next()
, etc), by
calling, (or invoking, the method.
println
or next
which belong to
System.out
and Scanner
respectively), we do not need to prefix the method name with the
class to which the method belongs.
public static void displayHelloWorld() { // Note the similarity to the first line of 'main'
…
}
main
is also a method
main
method
main
and terminates
after the last statement of main
has been executed.
Stdout
Hello world
Write a program containing a method, printA
, that prints an 'ASCII art' letter A:
A A A A A AAAAAAA A A A A A A
Code
public class AsciiA {
public static void main(String [] args) {
printA();
}
public static void printA() {
System.out.println(" A ");
System.out.println(" A A ");
System.out.println(" A A ");
System.out.println(" AAAAAAA ");
System.out.println(" A A ");
System.out.println(" A A ");
System.out.println("A A");
}
}
StdoutA A A A A AAAAAAA A A A A A A
main
method.
main
calling processOneStudent
;
therefore main
is the caller, and processOneStudents
the callee.
main
Write a program that prints the following figure:
!!!!! ***** ***** ***** ***** ***** !!!!!The program should contain the following methods:
printBox
— prints the entire figure
printBorder
— prints a line of 5 !
's
printStars
— prints a line of 5 *
's
printFiveLinesOfStars
— prints five (5) lines of stars by calling printStars
within a for loop
Codepublic class Box { public static void main(String [] args) { printBox(); } public static void printBox() { printBorder(); printFiveLinesOfStars(); printBorder(); } public static void printBorder() { System.out.println("!!!!!"); } public static void printFiveLinesOfStars() { for (int i = 1; i <= 5; i = i + 1) printStars(); } public static void printStars() { System.out.println("*****"); } }
printBorder
method
Stdout!!!!! ***** ***** ***** ***** ***** !!!!!
printFormLetter("Mr.", "Gerald", "Weiss");
()
's in the method header.
public static void printFormLetter(String salutation, String firstName, String lastName) {
…
}
printFormLetter("Mr.", "Gerald", "Weiss"); // all literals printFormLetter(sal, first, last); // all variables printFormLetter("Mr.", first, last); // mixture
Write a program containing a method printFormLetter
. printFormLetter
accepts two String
arguments, representing a first and last name, and uses it to produce a 'personalized' form letter.
Have main
print out two copies of the form letter to two different people.
Codepublic class FormLetter { public static void main(String [] args) { printFormLetter("Mr.", "Gerald", "Weiss"); System.out.println(); System.out.println(); printFormLetter("Professor", "David", "Arnow"); } public static void printFormLetter(String salutation, String first, String last) { System.out.println("Dear " + salutation + " " + last + ","); System.out.println(); System.out.println(" Hello " + first + ", we would like to inform you of our new "); System.out.println("chain of coffee houses in your area, geared to people like you. "); System.out.println(first + ", for a limited time, you can receive your own "); System.out.println("membership card, entitling you to 10% off your first 5 purchases, as well as a "); System.out.println("host of special offers. So hurry up, " + first + " and reply today!"); } }
String
, no compilation error is produced; insatead this
will result in a logic error.
StdoutDear Mr. Weiss, Hello Gerald, we would like to inform you of our new chain of coffee houses in your area, geared to people like you. Gerald, for a limited time, you can receive your own membership card, entitling you to 10% off your first 5 purchases, as well as a host of special offers. So hurry up, Gerald and reply today! Dear Professor Arnow, Hello David, we would like to inform you of our new chain of coffee houses in your area, geared to people like you. David, for a limited time, you can receive your own membership card, entitling you to 10% off your first 5 purchases, as well as a host of special offers. So hurry up, David and reply today!
return
statement
public static int max(int x, int y) { int result; if (x > y) result = x; else result = y; return result; }
max
:
public static int max(int x, int y) { if (x > y) return x; else return y; }
public static double sqrt(int number) { … } public static char calcGrade(int average) { … } public static int sumOf(20, 75) { … } /sums up the numbers from 20 to 75
d = 2 * sqrt(x); char grade = calcGrade(avg); System.out.println(sumOf(20, 75));
void
return type.
}
) of the method body (i.e., executing the last statement of the method)
has the same effect as a return statement.
Rewrite the grading program, adding a first and last name, and using the following methods:
void processStudent(Scanner scanner)
double calcAverage(int midterm, int finalExam)
char calcGrade(double average)
Codeimport java.util.*; public class Grader { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); System.out.println("Number of students to process: "); int numStudents = scanner.nextInt(); for (int i = 1; i <= numStudents; i = i + 1) processOneStudent(scanner); } public static void processOneStudent(Scanner scanner) { System.out.print("Last name: "); String lastName = scanner.next(); System.out.print("First name: "); String firstName = scanner.next(); System.out.print("Midterm: "); int midterm = scanner.nextInt(); System.out.print("Final: "); int finalExam = scanner.nextInt(); double average = calcAverage(midterm, finalExam); char grade = calcGrade(average); System.out.println("average: " + average + " grade: " + grade); } public static double calcAverage(int midterm, int finalExam) { return (midterm + finalExam) / 2.0; } public static char calcGrade(double average) { char grade; if (average >= 90) grade = 'A'; else if (average >= 80) grade = 'B'; else if (average >= 70) grade = 'C'; else if (average >= 60) grade = 'D'; else grade = 'F'; return grade; } }
main
as well as processOneStudent
, and thus
the Scanner
object is opened in main
and passed to processOneStudent
as
an argument
scanner
to main
, read in the
keyboard data (i.e., last name, first name, etc) in the loop bpdy and pass that data to processOneStudent
processOneStudent
method.
Stdin2 Weiss Gerald 80 95 Arnow David 65 75
StdoutLast name: First name: Midterm: Final: average: 87.5 grade: B Last name: First name: Midterm: Final: average: 70.0 grade: C
Here is a sample execution of the program. User input is in bold.
2 Last name: Weiss First name: Gerald Midterm: 80 Final: 95 average: 87.5 grade: B Last name: Arnow First name: David Midterm: 65 Final: 75 average: 70.0 grade: C
Write a method printASCIIArt(String s) that accepts a String argument and prints it as ASCII art
Codeimport java.util.*; public class AsciiArt { public static void main(String [] args) { // main is acting as a test driver, providing the ability to test the various letters Scanner scanner = new Scanner(System.in); System.out.print("string? "); String s = scanner.next(); printASCIIArt(s); } public static void printASCIIArt(String s) { for (int i = 0; i < s.length(); i = i + 1) printASCIIChar(s.charAt(i)); } public static void printASCIIChar(char c) { switch (c) { case 'A': printASCIIA(); break; case 'B': printASCIIB(); break; case 'C': printASCIIC(); break; case 'D': printASCIID(); break; … case 'Y': printASCIIY(); break; case 'Z': printASCIIZ(); break; case ' ': printASCIIBlank(); break; default: printUnknown(); break; } } … public static void printASCIIA() { System.out.println(" AAA "); System.out.println(" A A "); System.out.println(" A A "); System.out.println(" AAAAAAA "); System.out.println(" A A "); System.out.println(" A A "); System.out.println(" A A "); } public static void printASCIIB() { System.out.println(" BBBBBB "); System.out.println(" B B "); System.out.println(" B B "); System.out.println(" BBBBBB "); System.out.println(" B B "); System.out.println(" B B "); System.out.println(" BBBBBB "); } … public static void printASCIID() { // Test stub System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" D "); System.out.println(" "); System.out.println(" "); System.out.println(" "); } public static void printASCIIE() { System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" E "); System.out.println(" "); System.out.println(" "); System.out.println(" "); } public static void printASCIIF() {System.out.println("F goes here");} // Even shorter test stub public static void printASCIIG() {System.out.println("G goes here");} // Even shorter test stub … public static void printASCIIY() {System.out.println("Y goes here");} // Even shorter test stub public static void printASCIIZ() {System.out.println("Z goes here");} // Even shorter test stub public static void printASCIIBlank() { System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" "); } public static void printUnknown() { System.out.println(" ????? "); System.out.println(" ? ? "); System.out.println(" ? "); System.out.println(" ? "); System.out.println(" ? "); System.out.println(" "); System.out.println(" ? "); } }
StdinBYE!
Stdoutstring? BBBBBB B B B B BBBBBB B B B B BBBBBB Y goes here E ????? ? ? ? ? ? ?
Interactive Session
string? BYE!
BBBBBB
B B
B B
BBBBBB
B B
B B
BBBBBB
Y goes here
E
?????
? ?
?
?
?
?
Write a program that reads in an employee's last name, first name (strings), hours worked, and hourly rate (integers), calculates the gross wages, federal tax, state tax, and net earnings, and prints the results. Federal and state tax both use the same tax table:
Amount | % tax |
---|---|
Up to and including $200 | 0% |
$201 up to and including $400 | 10% |
$401 and up | 15% |
Federal tax is calculated first and deducted from the gross earning; the remainder is then subject to state tax
Codeimport java.util.*; public class Payroll { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); System.out.print("last name: "); String lastName = scanner.next(); System.out.print("first name: "); String firstName = scanner.next(); System.out.print("rate: "); int rate = scanner.nextInt(); System.out.print("hours: "); int hours = scanner.nextInt(); int gross = calculateGross(hours, rate); int federalTax = calcTax(gross); int net = gross - federalTax; int stateTax = calcTax(gross); // What's the bug? net = net - stateTax; printReport(lastName, firstName, hours, rate, gross, federalTax, stateTax, net); } public static int calculateGross(int hours, int rate) {return hours * rate;} public static int calcTax(int amount) { if (amount <= 200) return 0; else if (amount <= 400) return (int)(amount * .10); else return (int)(amount * .15); } public static void printReport(String lastName, String firstName, int hours, int rate, int gross, int federalTax, int stateTax, int net) { System.out.println(); System.out.println(); System.out.println("*** Payroll Report for " + lastName + ", " + firstName + " ***"); System.out.println(); System.out.println(hours + " hours worked @ $" + rate + " / hr"); System.out.println(); System.out.println("Gross wages: $" + gross); System.out.println(); System.out.println("--- Witholdings ---"); System.out.println("Federal tax: $" + federalTax); System.out.println("State tax : $" + stateTax); System.out.println(); System.out.println("Net earnings: $" + net); } }
StdinWeiss Gerald 20 32
Stdoutlast name: first name: rate: hours: *** Payroll Report for Weiss, Gerald *** 32 hours worked @ $20 / hr Gross wages: $640 --- Witholdings --- Federal tax: $96 State tax : $96 Net earnings: $448
Here is a sample execution of the program. User input is in bold. last name: Weiss first name: Gerald rate: 20 hours: 32 *** Payroll Report for Weiss, Gerald *** 32 hours worked @ $20 / hr Gross wages: $640 --- Witholdings --- Federal tax: $96 State tax : $96 Net earnings: $448