Day03-Workshop-Exception-Memory - Encapsulation-2021 - TranLQ
Day03-Workshop-Exception-Memory - Encapsulation-2021 - TranLQ
Upon successful completion of this workshop, you will have demonstrated the abilities to:
Requirements:
Part1: [5 points]
Write a Java program to accept a number and print out it. If the number is below 1 then a message
“the number is invalid” is printed out. Using do..while to input again, try-catch block to handle
errors.
1
Part 2: [5 points]
Write a Java program to accept a string and print out it. If the string does not match SExxx(x is
digit) then a message “the string is invalid” is printed out. Using do..while to input again.
Hint: In library class String, you should use the method matches() to do this, use try-catch
block and use throws to handle errors.
Background: In this workshop, you will use the pattern string( also called regular expression, see
more What is a Regular Expression? - Definition from Techopedia). You should read the document to
complete the exercise.
2
Task 1: use try-catch
At the row 9, use rules of the regular expression to create a pattern string “SExxx”, x is digit
3
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\FinalExam\Validation.java
1 /*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package FinalExam;
7
8 import java.util.Scanner;
9
10 /**
11 *
12 * @author Ly Quynh Tran
13 */
14 public class Validation {
15
4
16 public static Scanner in = new Scanner(System.in);
17
18 public static String checkInputString() {
19 //loop until user input correct
20 while (true) {
21 String result = in.nextLine().trim();
22 if (result.isEmpty()) {
23 System.err.println("Not empty");
24 System.out.print("Enter again: ");
25 } else {
26 return result;
27 }
28 }
29 }
30
31 public static int checkInputInt() {
32 while (true) {
33 try {
34 int result = Integer.parseInt(in.nextLine().trim());
35 return result;
36 } catch (NumberFormatException e) {
37 System.err.println("Please input number integer");
38 System.out.print("Enter again: ");
39 }
40 }
41
42 }
43 public static double checkInputDouble() {
44 while (true) {
45 try {
46 double result = Double.parseDouble((in.nextLine().trim()));
47 return result;
48 } catch (NumberFormatException e) {
49 System.err.println("Please input number integer");
50 System.out.print("Enter again: ");
51 }
52 }
53
54 }
55 }
56
5
❖ Question 01: The Student Class
Suppose that our application requires us to model students. A student has a name and an
address. We are required to keep track of the courses taken by each student, together with
the grades (between 0 and 100) for each of the courses. A student shall not take more
than 30 courses for the entire program. We are required to print all course grades, and
also the overall average grade.
We can design the Student class as shown in the class diagram. It contains the following
members:
private instance variables name (String), address (String), numCourses (int), course
(String[30]) and grades (int[30]). The
numCourses keeps track of the number of courses taken by this student so far. The
courses and grades are two parallel arrays,
storing the courses taken (e.g., {"IM101", "IM102", "IM103"}) and their respective
grades (e.g. {89, 56, 98}).
6
A constructor that constructs an instance with the given name and Address. It also
constructs the courses and grades arrays and set the numCourses to 0.
Getters for name and address; setter for address. No setter is defined for name as it is not
designed to be changed.
A toString(), which prints "name(address)".
A method addCourseGrade(course, grade), which appends the given course and grade
into the courses and grades arrays,
respectively; and increments numCourses.
A method printGrades(), which prints "name course1:grade1, course2:grade2,...".
A method getAverageGrade(), which returns the average grade of all the courses taken
The Student Class (Student.java)
1/**
2 * The student class models a student having courses and grades.
3 */
4public class Student {
5 // The private instance variables
6 private String name;
7 private String address;
8 // The courses taken and grades for the courses are kept in 2 parallel arrays
9 private String[] courses;
10 private int[] grades; // valid range is [0, 100]
11 private int numCourses; // Number of courses taken so far
12 private static final int MAX_COURSES = 30; // Maximum number of courses taken by studen
13
14 /** Constructs a Student instance with the given input */
15 public Student(String name, String address) {
16 this.name = name;
17 this.address = address;
18 courses = new String[MAX_COURSES]; // allocate arrays
19 grades = new int[MAX_COURSES];
20 numCourses = 0; // no courses so far
21 }
22
23 // The public getters and setters.
24 // No setter for name as it is not designed to be changed.
25 /** Returns the name */
26 public String getName() {
27 return this.name;
28 }
7
29 /** Returns the address */
30 public String getAddress() {
31 return this.address;
32 }
33 /** Sets the address */
34 public void setAddress(String address) {
35 this.address = address;
36 }
37
38 /** Returns a self-descriptive String */
39 public String toString() {
40 return name + "(" + address + ")";
41 }
42
43 /** Adds a course and grade */
44 public void addCourseGrade(String course, int grade) {
45 courses[numCourses] = course;
46 grades[numCourses] = grade;
47 ++numCourses;
48 }
49
50 /** Prints all courses and their grades */
51 public void printGrades() {
52 System.out.print(name);
53 for (int i = 0; i < numCourses; ++i) {
54 System.out.print(" " + courses[i] + ":" + grades[i]);
55 }
56 System.out.println();
57 }
58
59 /** Computes the average grade */
60 public double getAverageGrade() {
61 int sum = 0;
62 for (int i = 0; i < numCourses; ++i) {
63 sum += grades[i];
64 }
65 return (double)sum/numCourses;
66 }
67}
A Test Driver for the Student Class (TestStudent.java)
/**
* A test driver program for the Student class.
*/
public class TestStudent {
public static void main(String[] args) {
8
// Test constructor and toString()
Student ahTeck = new Student("Tan Ah Teck", "1 Happy Ave");
System.out.println(ahTeck); // toString()
//Tan Ah Teck(1 Happy Ave)
Notes : We used arrays In this example, which has several limitations. Arrays need to be pre-allocated
with a fixed-length. Furthermore, we need two parallel arrays to keep track of two entities. There are
advanced data structures that could represent these data better and more efficiently.
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\StudentCourseDemo\Cours
e.java
1 /*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package StudentCourseDemo;
7
8 /**
9 *
10 * @author Ly Quynh Tran
11 */
12 public class Course {
13 private String nameCourse;
14 private double grade;
15
9
16 public Course() {
17 }
18
19 public Course(String nameCourse, double grade) {
20 this.nameCourse = nameCourse;
21 this.grade = grade;
22 }
23
24 public String getNameCourse() {
25 return nameCourse;
26 }
27
28 public void setNameCourse(String nameCourse) {
29 this.nameCourse = nameCourse;
30 }
31
32 public double getGrade() {
33 return grade;
34 }
35
36 public void setGrade(double grade) {
37 this.grade = grade;
38 }
39
40 @Override
41 public String toString() {
42 return "Course{" + "nameCourse=" + nameCourse + ", grade=" + grade + '}';
43 }
44
45 }
46
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\StudentCourseDemo\Stude
nt.java
1 /*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package StudentCourseDemo;
7
10
8 import java.util.Scanner;
9
10 /**
11 *
12 * @author Ly Quynh Tran
13 */
14 public class Student {
15
16 public static Scanner in = new Scanner(System.in);
17 private int idStudent;
18 private String name;
19 private int numOfCourses = 0;
20 private Course[] myCourse;
21
22 public Student() {
23 }
24
25 public Student(int idStudent, String name) {
26 this.idStudent = idStudent;
27 this.name = name;
28 }
29
30 public Student(int idStudent, String name, Course[] myCourse) {
31 this.idStudent = idStudent;
32 this.name = name;
33 this.myCourse = myCourse;
34 }
35 // public Course[] addCourse(int numOfCourses )
36 // {
37 //
38 // }
39
40 public int getNumOfCourses() {
41 return numOfCourses;
42 }
43
44 public void setNumOfCourses(int numOfCourses) {
45 this.numOfCourses = numOfCourses;
46 }
47
48 public void addCourse() {
11
49 // Xin cap phat o nho cho mang chua cac khoa hoc
50 String n;
51 double g;
52 myCourse = new Course[numOfCourses];
53 System.out.println("Please enter the information of the courses: ");
54 for (int i = 0; i < myCourse.length; i++) {
55 System.out.print("Enter course name: ");
56 n = Student.in.nextLine();// Nhap 1 String tu keyboard
57 System.out.print("Enter grade: ");
58 g = Student.in.nextDouble();// Nhap 1 double tu keyboard
59 // An phim Enter sau khi nhap double , neu ko String tuong
60 // Phim no cua han
61 Student.in.nextLine();
62 Course tempCourse = new Course(n, g);
63 myCourse[i] = tempCourse;
64 }
65 }
66
67 public void studentDetails() {
68 System.out.println("Student ID: " + idStudent);
69 System.out.println("Student Name: " + name);
70 System.out.println("Course in this semester : ");
71 for (int i = 0; i < myCourse.length; i++) {
72 System.out.println(" + " + myCourse[i].toString());
73
74 }
75 }
76
77 public double getAverageGrades() {
78 double average = 0;
79 for (int i = 0; i < myCourse.length; i++) {
80 average = average + myCourse[i].getGrade();
81
82 }
83 average = (double) average / myCourse.length;
84 return average;
85 }
86
87 @Override
88 public String toString() {
89 return "Student{" + "idStudent=" + idStudent + ", name=" + name + '}';
12
90 }
91
92 }
93
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\StudentCourseDemo\Cours
e.java
1 /*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6 package StudentCourseDemo;
7
8 /**
9 *
10 * @author Ly Quynh Tran
11 */
12 public class Course {
13 private String nameCourse;
14 private double grade;
15
16 public Course() {
17 }
18
19 public Course(String nameCourse, double grade) {
20 this.nameCourse = nameCourse;
21 this.grade = grade;
22 }
23
24 public String getNameCourse() {
25 return nameCourse;
26 }
27
28 public void setNameCourse(String nameCourse) {
29 this.nameCourse = nameCourse;
30 }
31
32 public double getGrade() {
33 return grade;
34 }
13
35
36 public void setGrade(double grade) {
37 this.grade = grade;
38 }
39
40 @Override
41 public String toString() {
42 return "Course{" + "nameCourse=" + nameCourse + ", grade=" + grade + '}';
43 }
44
45 }
46
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\LineItem\Product.java
14
1 import java.text.NumberFormat;
2
3 public class Product
4{
5 private String code;
6 private String description;
7 private double price;
8
9 public Product()
10 {
11 code = "";
12 description = "";
13 price = 0;
14 }
15
16 public Product(String code, String description, double price)
17 {
18 this.code = code;
19 this.description = description;
20 this.price = price;
21 }
22
23 public void setCode(String code)
24 {
25 this.code = code;
26 }
27
28 public String getCode(){
29 return code;
30 }
31
32 public void setDescription(String description)
33 {
34 this.description = description;
35 }
36
37 public String getDescription()
38 {
39 return description;
40 }
41
15
42 public void setPrice(double price)
43 {
44 this.price = price;
45 }
46
47 public double getPrice()
48 {
49 return price;
50 }
51
52 public String getFormattedPrice()
53 {
54 NumberFormat currency = NumberFormat.getCurrencyInstance();
55 return currency.format(price);
56 }
57
58 }
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\LineItem\ProductDB.java
1 public class ProductDB
2{
3 public static Product getProduct(String productCode)
4 {
5 // In a more realistic application, this code would
6 // get the data for the product from a file or database
7 // For now, this code just uses if/else statements
8 // to return the correct product data
9
10 // create the Product object
11 Product product = new Product();
12
13 // fill the Product object with data
14 product.setCode(productCode);
15 if (productCode.equalsIgnoreCase("java"))
16 {
17 product.setDescription("Murach's Beginning Java");
18 product.setPrice(49.50);
19 }
20 else if (productCode.equalsIgnoreCase("jsps"))
16
21 {
22 product.setDescription("Murach's Java Servlets and JSP");
23 product.setPrice(49.50);
24 }
25 else if (productCode.equalsIgnoreCase("mcb2"))
26 {
27 product.setDescription("Murach's Mainframe COBOL");
28 product.setPrice(59.50);
29 }
30 else
31 {
32 product.setDescription("Unknown");
33 }
34 return product;
35 }
36 }
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\LineItem\Validator.java
1 import java.util.Scanner;
2
3 public class Validator
4{
5 public static String getString(Scanner sc, String prompt)
6 {
7 System.out.print(prompt);
8 String s = sc.next(); // read user entry
9 sc.nextLine(); // discard any other data entered on the line
10 return s;
11 }
12
13 public static int getInt(Scanner sc, String prompt)
14 {
15 int i = 0;
16 boolean isValid = false;
17 while (isValid == false)
18 {
19 System.out.print(prompt);
20 if (sc.hasNextInt())
21 {
17
22 i = sc.nextInt();
23 isValid = true;
24 }
25 else
26 {
27 System.out.println("Error! Invalid integer value. Try again.");
28 }
29 sc.nextLine(); // discard any other data entered on the line
30 }
31 return i;
32 }
33
34 public static int getInt(Scanner sc, String prompt,
35 int min, int max)
36 {
37 int i = 0;
38 boolean isValid = false;
39 while (isValid == false)
40 {
41 i = getInt(sc, prompt);
42 if (i <= min)
43 System.out.println(
44 "Error! Number must be greater than " + min + ".");
45 else if (i >= max)
46 System.out.println(
47 "Error! Number must be less than " + max + ".");
48 else
49 isValid = true;
50 }
51 return i;
52 }
53
54 public static double getDouble(Scanner sc, String prompt)
55 {
56 double d = 0;
57 boolean isValid = false;
58 while (isValid == false)
59 {
60 System.out.print(prompt);
61 if (sc.hasNextDouble())
62 {
18
63 d = sc.nextDouble();
64 isValid = true;
65 }
66 else
67 {
68 System.out.println("Error! Invalid decimal value. Try again.");
69 }
70 sc.nextLine(); // discard any other data entered on the line
71 }
72 return d;
73 }
74
75 public static double getDouble(Scanner sc, String prompt,
76 double min, double max)
77 {
78 double d = 0;
79 boolean isValid = false;
80 while (isValid == false)
81 {
82 d = getDouble(sc, prompt);
83 if (d <= min)
84 System.out.println(
85 "Error! Number must be greater than " + min + ".");
86 else if (d >= max)
87 System.out.println(
88 "Error! Number must be less than " + max + ".");
89 else
90 isValid = true;
91 }
92 return d;
93 }
94 }
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\LineItem\LineItem.java
1 import java.text.NumberFormat;
2
3 public class LineItem
4{
5 private Product product;
19
6 private int quantity;
7 private double total;
8
9 public LineItem()
10 {
11 this.product = new Product();
12 this.quantity = 0;
13 this.total = 0;
14 }
15
16 public LineItem(Product product, int quantity)
17 {
18 this.product = product;
19 this.quantity = quantity;
20 }
21
22 public void setProduct(Product product)
23 {
24 this.product = product;
25 }
26
27 public Product getProduct()
28 {
29 return product;
30 }
31
32 public void setQuantity(int quantity)
33 {
34 this.quantity = quantity;
35 }
36
37 public int getQuantity()
38 {
39 return quantity;
40 }
41
42 public double getTotal()
43 {
44 this.calculateTotal();
45 return total;
46 }
20
47
48 private void calculateTotal()
49 {
50 double price = product.getPrice();
51 total = quantity * price;
52 }
53
54 public String getFormattedTotal()
55 {
56 NumberFormat currency = NumberFormat.getCurrencyInstance();
57 return currency.format(this.getTotal());
58 }
59 }
C:\Users\Ly Quynh
Tran\Documents\NetBeansProjects\UDAPro192\src\LineItem\LineItemApp.java
1
2 import java.util.Scanner;
3
4 public class LineItemApp {
5
6 public static void main(String args[]) {
7 // display a welcome message
8 System.out.println("Welcome to the Line Item Calculator");
9 System.out.println();
10
11 // create 1 or more line items
12 Scanner sc = new Scanner(System.in);
13 String choice = "y";
14 while (choice.equalsIgnoreCase("y")) {
15 // get the input from the user
16 String productCode = Validator.getString(sc,
17 "Enter product code: ");
18 int quantity = Validator.getInt(sc,
19 "Enter quantity: ", 0, 1000);
20
21 // get the Product object
22 Product product = ProductDB.getProduct(productCode);
23
24 // create the LineItem object
21
25 LineItem lineItem = new LineItem(product, quantity);
26
27 // display the output
28 System.out.println();
29 System.out.println("LINE ITEM");
30 System.out.println("Code: " + product.getCode());
31 System.out.println("Description: " + product.getDescription());
32 System.out.println("Price: " + product.getFormattedPrice());
33 System.out.println("Quantity: " + lineItem.getQuantity());
34 System.out.println("Total: "
35 + lineItem.getFormattedTotal() + "\n");
36
37 // see if the user wants to continue
38 choice = Validator.getString(sc, "Continue? (y/n): ");
39 System.out.println();
40 }
41 }
42 }
43
22