Homework 1
Homework 1
The goal: A class contains multiple methods, with one method calling
another method.
Requirement: Define a class named “Calculator” that contains three
methods:
(1) The first method is named “add”, and it can calculate the sum of two
numbers.
(2) The second method is named “printSum”, it should be a non-static
method (i.e.,
instance method) with two arguments and should print the sum of two
numbers. It
needs to call the first method.
(3) The third method is the “main” function, which needs to call the second
method
and provide two actual parameters to it.
Code:
package Default;
2. Modify all three methods in the previous example to be static methods, and
ensure that the modified program can still run.
Code:
package Default;
class Calculator {
// Static method to calculate the sum of two numbers
public static int add(int a, int b) {
return a + b;
}
Code:
package Default;
import java.util.ArrayList;
import java.util.Iterator;
// Method to create
public static ArrayList<String> createFruitList() {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Grape");
fruits.add("Pineapple");
return fruits;
}
4. Write a program that removes all numbers between 1 and 100 that are
multiples of 9 or contain the digit 9 (For example, 9 and 19 should be
removed).
Print the remaining numbers.
Hints: You can
(1) use ArrayList<Integer> to store the numbers from 1 to 100.
(2) use String.valueOf(num) to convert the int type num to a String in order
to check
if it contains the digit “9”.
Code:
package Default;
import java.util.ArrayList;
5. The goal: familiar with Constructor Overloading and how to use it.
Requirement: Create a Person class with two fields: name and age.
Create three different constructors:
(1) The first constructor takes no parameters, assigns the name as
"Unknown" and
the age as 0.
(2) The second constructor takes one parameter and uses it to initialize the
name.
(3) The third constructor takes two parameters and uses them to initialize
both the
name and age.
(4) Create a method named printInfo() to print the name and age of the
Person.
(5) In the main function, use three constructors to create three objects and
call
printInfo() to print their information.
(6) The program should use this keyword to assign values to the fields.
Code:
package Default;
class Person {
private String name;
private int age;