commit 51d92a3aa451c6c16098a3dffbac13f3f3d6d5d2 Author: Devoalda Date: Sun Dec 17 22:16:09 2023 +0800 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..12acf44 --- /dev/null +++ b/.gitignore @@ -0,0 +1,408 @@ +### Java template +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### JetBrains template +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### TeX template +## Core latex/pdflatex auxiliary files: +*.aux +*.lof +*.lot +*.fls +*.out +*.toc +*.fmt +*.fot +*.cb +*.cb2 +.*.lb + +## Intermediate documents: +*.dvi +*.xdv +*-converted-to.* +# these rules might exclude image files for figures etc. +# *.ps +# *.eps +# *.pdf + +## Generated if empty string is given at "Please type another file name for output:" +.pdf + +## Bibliography auxiliary files (bibtex/biblatex/biber): +*.bbl +*.bcf +*.blg +*-blx.aux +*-blx.bib +*.run.xml + +## Build tool auxiliary files: +*.fdb_latexmk +*.synctex +*.synctex(busy) +*.synctex.gz +*.synctex.gz(busy) +*.pdfsync + +## Build tool directories for auxiliary files +# latexrun +latex.out/ + +## Auxiliary and intermediate files from other packages: +# algorithms +*.alg +*.loa + +# achemso +acs-*.bib + +# amsthm +*.thm + +# beamer +*.nav +*.pre +*.snm +*.vrb + +# changes +*.soc + +# comment +*.cut + +# cprotect +*.cpt + +# elsarticle (documentclass of Elsevier journals) +*.spl + +# endnotes +*.ent + +# fixme +*.lox + +# feynmf/feynmp +*.mf +*.mp +*.t[1-9] +*.t[1-9][0-9] +*.tfm + +#(r)(e)ledmac/(r)(e)ledpar +*.end +*.?end +*.[1-9] +*.[1-9][0-9] +*.[1-9][0-9][0-9] +*.[1-9]R +*.[1-9][0-9]R +*.[1-9][0-9][0-9]R +*.eledsec[1-9] +*.eledsec[1-9]R +*.eledsec[1-9][0-9] +*.eledsec[1-9][0-9]R +*.eledsec[1-9][0-9][0-9] +*.eledsec[1-9][0-9][0-9]R + +# glossaries +*.acn +*.acr +*.glg +*.glo +*.gls +*.glsdefs +*.lzo +*.lzs +*.slg +*.slo +*.sls + +# uncomment this for glossaries-extra (will ignore makeindex's style files!) +# *.ist + +# gnuplot +*.gnuplot +*.table + +# gnuplottex +*-gnuplottex-* + +# gregoriotex +*.gaux +*.glog +*.gtex + +# htlatex +*.4ct +*.4tc +*.idv +*.lg +*.trc +*.xref + +# hyperref +*.brf + +# knitr +*-concordance.tex +# TODO Uncomment the next line if you use knitr and want to ignore its generated tikz files +# *.tikz +*-tikzDictionary + +# listings +*.lol + +# luatexja-ruby +*.ltjruby + +# makeidx +*.idx +*.ilg +*.ind + +# minitoc +*.maf +*.mlf +*.mlt +*.mtc[0-9]* +*.slf[0-9]* +*.slt[0-9]* +*.stc[0-9]* + +# minted +_minted* +*.pyg + +# morewrites +*.mw + +# newpax +*.newpax + +# nomencl +*.nlg +*.nlo +*.nls + +# pax +*.pax + +# pdfpcnotes +*.pdfpc + +# sagetex +*.sagetex.sage +*.sagetex.py +*.sagetex.scmd + +# scrwfile +*.wrt + +# svg +svg-inkscape/ + +# sympy +*.sout +*.sympy +sympy-plots-for-*.tex/ + +# pdfcomment +*.upa +*.upb + +# pythontex +*.pytxcode +pythontex-files-*/ + +# tcolorbox +*.listing + +# thmtools +*.loe + +# TikZ & PGF +*.dpth +*.md5 +*.auxlock + +# titletoc +*.ptc + +# todonotes +*.tdo + +# vhistory +*.hst +*.ver + +# easy-todo +*.lod + +# xcolor +*.xcp + +# xmpincl +*.xmpi + +# xindy +*.xdy + +# xypic precompiled matrices and outlines +*.xyc +*.xyd + +# endfloat +*.ttt +*.fff + +# Latexian +TSWLatexianTemp* + +## Editors: +# WinEdt +*.bak +*.sav + +# Texpad +.texpadtmp + +# LyX +*.lyx~ + +# Kile +*.backup + +# gummi +.*.swp + +# KBibTeX +*~[0-9]* + +# TeXnicCenter +*.tps + +# auto folder when using emacs and auctex +./auto/* +*.el + +# expex forward references with \gathertags +*-tags.tex + +# standalone packages +*.sta + +# Makeindex log files +*.lpz + +# xwatermark package +*.xwm + +# REVTeX puts footnotes in the bibliography by default, unless the nofootinbib +# option is specified. Footnotes are the stored in a file with suffix Notes.bib. +# Uncomment the next line to have this generated file ignored. +#*Notes.bib + + diff --git a/Exam/FIB.java b/Exam/FIB.java new file mode 100644 index 0000000..9669828 --- /dev/null +++ b/Exam/FIB.java @@ -0,0 +1,210 @@ +package Exam; + +import java.util.*; + +public class FIB { + public static int fib(int a){ + if(a == 0 || a == 1) return a; + return fib(a-1) + fib(a-2); + } + + public static int fac(int a){ + if (a <= 1) return a; + else return a * fac(a - 1); + } + + public static int[] mergesort(int[] arr){ + if (arr.length <= 1) { + return arr; + } + + int mid = arr.length >> 1; + + int[] left = new int[mid]; + int[] right = new int[arr.length - mid]; + + for (int i = 0; i < mid; i++){ + left[i] = arr[i]; + } + for (int i = mid; i < arr.length; i++){ + right[i - mid] = arr[i]; + } + left = mergesort(left); + right = mergesort(right); + + return merge(left, right); + } + + public static int[] merge(int[] a, int[] b){ + int aindex = 0, bindex = 0; + int [] result = new int[a.length + b.length]; + int aSize = a.length, bSize = b.length; + + while (aindex < a.length && bindex < bSize){ + if (a[aindex] < b[bindex]){ + result[aindex + bindex] = a[aindex]; + aindex++; + } + else{ + result[aindex + bindex] = b[bindex]; + bindex++; + } + } + + while (aindex < aSize){ + result[aindex + bindex] = a[aindex]; + aindex++; + } + + while (bindex < bSize){ + result[aindex + bindex] = b[bindex]; + bindex++; + } + + return result; + } + + public static ArrayList mergesort(ArrayList arr){ + if (arr.size() <= 1) { + return arr; + } + + int mid = arr.size() >> 1; + + ArrayList left = new ArrayList<>(); + ArrayList right = new ArrayList<>(); + + for (int i = 0; i < mid; i++){ + left.add(arr.get(i)); + } + for (int i = mid; i < arr.size(); i++){ + right.add(arr.get(i)); + } + left = mergesort(left); + right = mergesort(right); + + return merge(left, right); + } + + public static ArrayList merge(ArrayList a, ArrayList b){ + ArrayList c = new ArrayList<>(); + int aindex = 0, bindex = 0; + int aSize = a.size(), bSize = b.size(); + + while (aindex < aSize && bindex < bSize){ + if (a.get(aindex) < b.get(bindex)){ + c.add(a.get(aindex)); + aindex++; + } + else{ + c.add(b.get(bindex)); + bindex++; + } + } + + while (aindex < aSize){ + c.add(a.get(aindex)); + aindex++; + } + + while (bindex < bSize){ + c.add(b.get(bindex)); + bindex++; + } + + return c; + } + + public static int BSearc(int[] arr, int num){ + int low = 0, high = arr.length; + while (low <= high){ + int mid = (low + high) >> 1; + if (arr[mid] == num) return mid; + else if (arr[mid] < num) low = mid + 1; + else high = mid - 1; + } + return -1; + } + + public static void main(String[] args) { + int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9,10}; + int num = 4; + System.out.println(BSearc(arr, num)); + } +} +class person{ + private String name; + private int age; + + public person(String name, int age){ + System.out.println("Person constructor"); + this.name = name; + this.age = age; + } + + public person(String name){ + this(name, 0); + } + + public person(int age){ + this("John", age); + } + + public String getName(){ + return this.name; + } + public void setName(String name) { + this.name = name; + } + + public int getAge(){ + return this.age; + } + public void setAge(int age) { + this.age = age; + } +} + +class Student extends person{ + private int GPA; + private double height; + public Student(){ + this("John", 0, 0); + } + public Student(String name, int age, int GPA){ + super(name, age); + this.GPA = GPA; + } + public Student(double height){ + this("John", 0, 0); + this.height = height; + System.out.println("Student height: " + height); + } + + private Student(String name, int GPA){ + this(name, 0, GPA); + } + + public Student(int GPA, int age, String name){ + this(name, age, GPA); + } + + public Student(int age, String name){ + this(name, age, 0); + } + + public void setAge(int age){ + System.out.printf("Student age: %d \n", age); + super.setAge(age); + } + public static void main(String... args){ + var s = new Student(3); + System.out.println(s.getAge()); + } +} + +class myexception extends Exception{ + public myexception(String message){ + super(message); + } +} \ No newline at end of file diff --git a/Exam/shapes.java b/Exam/shapes.java new file mode 100644 index 0000000..de3b65e --- /dev/null +++ b/Exam/shapes.java @@ -0,0 +1,153 @@ +package Exam; + +import java.util.ArrayList; + +public abstract class shapes { + private int length, breadth, radius; + + public shapes(){ + print("Here"); + + } + public shapes(int length, int breadth){ + this.length = length; + this.breadth = breadth; + } + + public shapes(int radius){ + this.radius = radius; + } + + public shapes(float radius){ + this.radius = (int) radius; + } + + public int getArea(){ + return this.length * this.breadth; + } + + public float getCircleArea(){ + return (float) (this.radius * this.radius * 3.14); + } + + public int getPerimeter(){ + return 2 * (this.length + this.breadth); + } + + public float getCirclePerimeter(){ + return (float) (2 * this.radius * 3.14); + } + + public static int shape(int length, int breadth){ + return length * breadth; + } + + public static double shape(double radius){ + return radius * radius * 3.14; + } + public t shape(t a){ + return a; + } + + // toString() method + public String toString(){ +// System.out.println("Length: " + this.length + " Breadth: " + this.breadth); + if (this.length == 0 && this.breadth == 0){ + return "Radius: " + this.radius; + } + else { + return "Length: " + this.length + " Breadth: " + this.breadth; + } + } + + public static void print() { + print(null); + } + + + public static void print(t a){ + System.out.println(a); + } +} + +class shape2 extends shapes{ + + public shape2(){ + + } + public shape2(int length, int breadth){ + super(length, breadth); + } + + public String toString(){ + print(super.toString()); + return"This is shape2 class"; + } + + public static void main(String... args) { + shape2 s = new shape2(); +// System.out.println(s); + try{ + print("Hello"); + } + finally { + print("Finally"); + } + } +} + +class testMarks { + // Generic score + public static String getScore(double score){ +// double score; +// +// try { +// score = Double.parseDouble(a.toString()); +// } +// catch (Exception e){ +// return "E"; +// } + + if (75 <= score && score <= 100) { + return "A"; + } else if (60 <= score && score < 75) { + return "B"; + } else if (40 <= score && score < 60) { // 40 <= score < 60 + return "C"; + } else if (0 <= score && score < 40) { + return "F"; + } + else { + return "E"; + } + } + + public String toString(){ + return "This is testMarks class"; + } + + public static void main(String... args) { + testMarks t = new testMarks(); + System.out.println(t); + System.out.println(getScore(90)); + } +} + +class rec{ + public void printname(){ + System.out.println("Val a"); + } +} + +class sq extends rec{ + public void printname(){ + System.out.println("Val b"); + } +} + +class test3{ + public static void main(String... args) { + sq s = new sq(); + s.printname(); + } +} \ No newline at end of file diff --git a/Exam/testMarksTest.java b/Exam/testMarksTest.java new file mode 100644 index 0000000..b4cba0b --- /dev/null +++ b/Exam/testMarksTest.java @@ -0,0 +1,43 @@ +package Exam; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class testMarksTest { + @Before + public void setUp(){ + System.out.println("Test Start"); + } + @After + public void tearDown(){ + System.out.println("Test End"); + } + + @Test + public void testGetGrade() { + // Test normal (Typical Testing) + assertEquals("Wrong Grade", "A", testMarks.getScore(90)); + assertEquals("Wrong Grade", "B", testMarks.getScore(70)); + assertEquals("Wrong Grade", "C", testMarks.getScore(50)); + assertEquals("Wrong Grade", "F", testMarks.getScore(30)); + + // Test boundary 3 Cases + assertEquals("Wrong Grade", "A", testMarks.getScore(76)); + assertEquals("Wrong Grade", "A", testMarks.getScore(75)); + assertEquals("Wrong Grade", "B", testMarks.getScore(74)); + + // Test boundary 3 Cases + assertEquals("Wrong Grade", "B", testMarks.getScore(61)); + assertEquals("Wrong Grade", "B", testMarks.getScore(60)); + assertEquals("Wrong Grade", "C", testMarks.getScore(59)); + + // Test Illegal Argument + assertEquals("Wrong Grade", "E", testMarks.getScore(10000)); + assertEquals("Wrong Grade", "E", testMarks.getScore(-1)); + assertEquals("Wrong Grade", "E", testMarks.getScore(100.1)); + } + +} \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1eb40da --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Woon Jun Wei + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Playground/ArraylistTest.java b/Playground/ArraylistTest.java new file mode 100644 index 0000000..2053f8c --- /dev/null +++ b/Playground/ArraylistTest.java @@ -0,0 +1,46 @@ +package Playground; +import java.util.ArrayList; + +public class ArraylistTest { + public static void main(String[] args) { + ArrayList intList = new ArrayList(); + + intList.add(1); + intList.add(4); + intList.add(2); + intList.add(9); + intList.add(3); + + System.out.println("Before Sort"); + System.out.println(intList); + System.out.println("\nBubble Sort\n"); + sort(intList); + System.out.println("After Sort"); + System.out.println(intList); + + System.out.println("Max: " + max(intList)); + } + + public static int max(ArrayList intList) { + int i, max = intList.get(0); + + for (i = 0; i< intList.size(); i++){ + if (intList.get(i) > max){ + max = intList.get(i); + } + } + return max; + } + public static ArrayList sort(ArrayList intList){ + for (int i = 0; i< intList.size() -1; i++){ + for (int j = 0; j < intList.size() - i - 1; j++){ + if (intList.get(j) > intList.get(j + 1)) { + int temp = intList.get(j); + intList.set(j, intList.get(j + 1)); + intList.set(j + 1, temp); + } + } + } + return intList; + } +} diff --git a/Playground/ExceptionsP/CalException.java b/Playground/ExceptionsP/CalException.java new file mode 100644 index 0000000..91c0e73 --- /dev/null +++ b/Playground/ExceptionsP/CalException.java @@ -0,0 +1,65 @@ +package Playground.ExceptionsP; + +public class CalException extends Throwable{ + private double amount; + public CalException(double amount){ + this.amount = amount; + } + public CalException(String message, double amount){ + super(message); + this.amount = amount; + } + + public double getAmount(){ + return amount; + } + + public String toString(){ + return "CalException: " + amount; + } + +} + +class Calculator{ + private int A, B; + public Calculator(int A, int B){ + this.A = A; + this.B = B; + } + public int sum() throws CalException{ + if (A + B > 100){ + throw new CalException("Sum is greater than 100", A + B); + } + return A + B; + } + public int sub() throws CalException{ + if (A - B < 0){ + throw new CalException("Sub is less than 0", A - B); + } + return A - B; + } + + public float div() throws CalException{ + if (B == 0){ + throw new CalException("Div by 0", 0); + } + return A / B; + } + + public static void main(String[] args){ + Calculator c = new Calculator(10, 0); + try { + System.out.println(c.sum()); + System.out.println(c.sub()); + System.out.println((float) c.div()); + } catch (CalException e) { + System.out.println(e.getMessage()); + System.out.println(e.getAmount()); + System.out.println(e.toString()); + } + finally{ + System.out.println("Finally"); + } + } + +} diff --git a/Playground/ExceptionsP/CalculatorTest.java b/Playground/ExceptionsP/CalculatorTest.java new file mode 100644 index 0000000..cbc2272 --- /dev/null +++ b/Playground/ExceptionsP/CalculatorTest.java @@ -0,0 +1,31 @@ +package Playground.ExceptionsP; + +import org.junit.After; +import org.junit.Before; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CalculatorTest { + Calculator c = new Calculator(10, 0); + + @Test + void sum() throws CalException { + System.out.println("Sum: " + c.sum()); + assertEquals(10, c.sum()); + } + + @Test + void sub() throws CalException { + assertEquals(10, c.sub()); + } + + @Test + void div() throws CalException { + assertThrows(CalException.class, () -> c.div()); + } + + @After + public void tearDown() throws Exception { + } +} \ No newline at end of file diff --git a/Playground/genericP/genericsPractice.java b/Playground/genericP/genericsPractice.java new file mode 100644 index 0000000..ff64b97 --- /dev/null +++ b/Playground/genericP/genericsPractice.java @@ -0,0 +1,40 @@ +package Playground.genericP; + +import java.util.ArrayList; + +public class genericsPractice { + public static void main(String[] args){ + ArrayList list = new ArrayList<>(); + Test t = new Test<>(); + Test r = new Test<>(); + + t.set("Hello"); + r.set("World"); + + list.add(t); + list.add(r); + + for (Test c : list){ + System.out.println(c.get()); + } + + } + + +} + +class Test{ + private T t; + public void set(T t){ + this.t = t; + } + public T get(){ + return t; + } + + public static void main(String[] args) { + Test i = new Test<>(); + i.set(10.0f); + System.out.println(i.get()); + } +} diff --git a/Playground/sqliteTest/sqliteTest.java b/Playground/sqliteTest/sqliteTest.java new file mode 100644 index 0000000..4fe6190 --- /dev/null +++ b/Playground/sqliteTest/sqliteTest.java @@ -0,0 +1,22 @@ +package Playground.sqliteTest; +import java.sql.*; + + +public class sqliteTest { + public static void main(String[] args){ + String connectionURL = "jdbc:sqlite:src/Playground/sqliteTest/test.db"; + // Connect to Database + try{ + Connection conn = DriverManager.getConnection("jdbc:sqlite:src/Playground/sqliteTest/test.sqlite"); + Statement stmt = conn.createStatement(); + stmt.execute("CREATE TABLE IF NOT EXISTS test (name TEXT)"); + ResultSet rs = stmt.executeQuery("SELECT * FROM test"); + while(rs.next()){ + System.out.println(rs.getString("name")); + } + } catch (SQLException e){ + System.out.println(e.getMessage()); + } + + } +} diff --git a/Playground/testcase/grades.java b/Playground/testcase/grades.java new file mode 100644 index 0000000..3f6bb07 --- /dev/null +++ b/Playground/testcase/grades.java @@ -0,0 +1,27 @@ +package Playground.testcase; +import java.util.ArrayList; + +public class grades { +// public static String getGrade(int score){ +// return getString(score); +// } + public static void main(String[] args){ + ArrayList list = new ArrayList<>(); + list.add(1); + list.add(2); + + int a = list.get(0); + System.out.println(a); + + } +} + +abstract class test{ + public abstract void test1(); + +} +abstract class test2 extends test{ + public void test1(){ + System.out.println("test"); + } +} diff --git a/Playground/testcase/gradesTest.java b/Playground/testcase/gradesTest.java new file mode 100644 index 0000000..10363a6 --- /dev/null +++ b/Playground/testcase/gradesTest.java @@ -0,0 +1,47 @@ +package Playground.testcase; + +import org.junit.After; +import org.junit.Test; +import static org.junit.Assert.*; + +public class gradesTest { + +// @Test +// public void testGetGrade() { +// // Test normal (Typical Testing) +// assertEquals("Wrong Grade", grades.getGrade(90), "A"); +// assertEquals("Wrong Grade", grades.getGrade(70), "B"); +// assertEquals("Wrong Grade", grades.getGrade(50), "C"); +// assertEquals("Wrong Grade", grades.getGrade(30), "F"); +// +// // Test boundary 3 cases +// assertEquals("Wrong Grade", grades.getGrade(76), "A"); +// assertEquals("Wrong Grade", grades.getGrade(75), "A"); +// assertEquals("Wrong Grade", grades.getGrade(74), "B"); +// +// // Test boundary 3 cases +// assertEquals("Wrong Grade", grades.getGrade(61), "B"); +// assertEquals("Wrong Grade", grades.getGrade(60), "B"); +// assertEquals("Wrong Grade", grades.getGrade(59), "C"); +// +// // Test Illegal Argument +// assertEquals("Wrong Grade", grades.getGrade(10000), "E"); +// } +// +// @Test +// public void testBoundaryofA(){ +// assertEquals("A", grades.getGrade(76), "Wrong Grade"); +// assertEquals("A", grades.getGrade(75), "Wrong Grade"); +// assertNotEquals("A", grades.getGrade(74), "Wrong Grade"); +// } +// +// @Test +// public void testIllegalArgument(){ +// assertEquals("E", grades.getGrade(10000), "Wrong Grade"); +// assertEquals("E", grades.getGrade(-1), "Wrong Grade"); +// } +// +// @After +// public void tearDown() throws Exception { +// } +} \ No newline at end of file diff --git a/Playground/testcase/tmp.java b/Playground/testcase/tmp.java new file mode 100644 index 0000000..45e5a04 --- /dev/null +++ b/Playground/testcase/tmp.java @@ -0,0 +1,13 @@ +package Playground.testcase; + +abstract class tmp extends grades{ + public void test1(){ + System.out.println("test"); + } + + public static void main(String[] args){ + tmp t = new tmp() { + }; + t.test1(); + } +} diff --git a/Practice/School/Chile.java b/Practice/School/Chile.java new file mode 100644 index 0000000..478625d --- /dev/null +++ b/Practice/School/Chile.java @@ -0,0 +1,19 @@ +package Practice.School; + +public class Chile extends Parent { + + public Chile(){ + int age = super.getAge(); + } + public void print(){ + System.out.println("Hello child"); + + } + + public static void main(String[] args) { + Chile chile = new Chile(); + System.out.println(chile.getAge()); + + } +} + diff --git a/Practice/School/Dataset.java b/Practice/School/Dataset.java new file mode 100644 index 0000000..1c34c43 --- /dev/null +++ b/Practice/School/Dataset.java @@ -0,0 +1,10 @@ +package Practice.School; + +public class Dataset { + + int[] id = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + public int[] getId() { + return id; + } +} diff --git a/Practice/School/Developers/BackendDeveloper.java b/Practice/School/Developers/BackendDeveloper.java new file mode 100644 index 0000000..619b20a --- /dev/null +++ b/Practice/School/Developers/BackendDeveloper.java @@ -0,0 +1,28 @@ +package Practice.School.Developers; + +public class BackendDeveloper extends Developer{ + private String language; + private String name; + public BackendDeveloper(String name, int age, String job, String device, String lan){ + super(name, age, job, device); + this.name = name; + this.language = lan; + } + public BackendDeveloper(){ + this("John", 20, "Backend Developer", "Mac", "Java"); + } + + @Override + public void code() { + System.out.println("My name is " + name + " and I am a " + job + " and I am coding in " + language); + } + + @Override + public void debug() { + System.out.println("I am debugging in " + language); + } + + public void code(String language){ // Overloading + System.out.println("I am coding in " + language); + } +} diff --git a/Practice/School/Developers/Developer.java b/Practice/School/Developers/Developer.java new file mode 100644 index 0000000..1d5ed23 --- /dev/null +++ b/Practice/School/Developers/Developer.java @@ -0,0 +1,34 @@ +package Practice.School.Developers; + +import Practice.School.doWork; +import Practice.School.human; + +public abstract class Developer extends human implements doWork { + private String Device; + + public Developer(String name, int age, String job, String device){ + super(name, age, job); + this.Device = device; + } + public Developer(String device){ + super("John", 20, "Developer"); + this.Device = device; + } + + public Developer(){ + super("John", 20, "Developer"); + this.Device = "Mac"; + } + public void doWork(String WorkType){ + System.out.println("I am doing " + WorkType + " on my " + Device); + } + public void doWork(){ // Overloading + System.out.println("I am doing work"); + } + public void rest() { + System.out.println("I am on a break"); + } + public abstract void code(); + + public abstract void debug(); +} diff --git a/Practice/School/HumanMainClass.java b/Practice/School/HumanMainClass.java new file mode 100644 index 0000000..2c73b55 --- /dev/null +++ b/Practice/School/HumanMainClass.java @@ -0,0 +1,65 @@ +package Practice.School; + +import Practice.School.Developers.BackendDeveloper; + +public class HumanMainClass { + public static void main(String[] args){ + //Polymorphism + human h1 = new student("John", 20, "UoG", 5.00); + System.out.print("H1 starts here: "); + h1.sayHello(); //From Student + System.out.println(); + ((student) h1).doWork(); //I am doing work + + ((student)h1).getGPA(); // Cast to student to access GPA + + BackendDeveloper b1 = new BackendDeveloper("John", 20, "UoG", "Mac", "Java"); + + human h2 = new BackendDeveloper("John", 20, "Dev", "Mac", "Java"); + + System.out.println("\nH2 starts here"); + // Casting to access methods + ((BackendDeveloper)(h2)).code(); //Overriding From abstract class Developer + ((BackendDeveloper)(h2)).code("Java"); //Overloading + ((BackendDeveloper)(h2)).debug(); + ((BackendDeveloper)(h2)).doWork("Project"); + ((BackendDeveloper)(h2)).rest(); + h2.sayHello(); //Using polymorphism + + // polymorphism + System.out.println("\nB1 starts here"); + b1.code(); + b1.debug(); + b1.doWork("Project"); + b1.rest(); + + //BackendDeveloper b = new BackendDeveloper("John", 20, "UoG", "Mac", "Java"); + BackendDeveloper b = new BackendDeveloper(); + b.doWork("game"); + + Dataset DA = new Dataset(); + int [] x = DA.getId(); + + for(int i = 0; i < x.length; i++){ + System.out.println(x[i]); + } + //Output: +// H1 starts here: From Student +// I am doing work +// My GPA is 5.0 +// +// H2 starts here +// My name is John and I am coding in Java +// I am coding in Java +// I am debugging in Java +// I am doing Project on my Mac +// I am on a break +// Hello, my name is John and I am 20 years old. +// +// B1 starts here +// My name is John and I am coding in Java +// I am debugging in Java +// I am doing Project on my Mac +// I am on a break + } +} diff --git a/Practice/School/Parent.java b/Practice/School/Parent.java new file mode 100644 index 0000000..2071566 --- /dev/null +++ b/Practice/School/Parent.java @@ -0,0 +1,19 @@ +package Practice.School; + +public class Parent { + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + private int age; + public Parent(){ + age = 10; + } + public void print(){ + System.out.println("Hello parent"); + } +} diff --git a/Practice/School/doWork.java b/Practice/School/doWork.java new file mode 100644 index 0000000..06d1509 --- /dev/null +++ b/Practice/School/doWork.java @@ -0,0 +1,9 @@ +package Practice.School; + +public interface doWork { + static final int MAX_WORK = 10; + public void doWork(String WorkType); + + public void rest(); + +} diff --git a/Practice/School/human.java b/Practice/School/human.java new file mode 100644 index 0000000..2d57dd9 --- /dev/null +++ b/Practice/School/human.java @@ -0,0 +1,17 @@ +package Practice.School; + +public class human { + private String name; + protected int age; + protected String job; + + public human(String name, int age, String job){ + this.name = name; + this.age = age; + this.job = job; + } + + public void sayHello(){ + System.out.println("Hello, my name is " + name + " and I am " + age + " years old."); + } +} diff --git a/Practice/School/student.java b/Practice/School/student.java new file mode 100644 index 0000000..a160e51 --- /dev/null +++ b/Practice/School/student.java @@ -0,0 +1,33 @@ +package Practice.School; + +public class student extends human implements doWork{ + private String School; + private double GPA; + + public student(String name, int age, String school, double GPA){ + super(name, age, "Student"); + this.School = school; + this.GPA = GPA; + } + + public void sayHello(){//Override + System.out.print("From Student"); + } + + public void doWork() { + System.out.println("I am doing work"); + } + + @Override + public void doWork(String WorkType) { + System.out.println("I am doing " + WorkType); + + } + + public void rest() { + System.out.println("I am resting"); + } + public void getGPA(){ + System.out.println("My GPA is " + GPA); + } +} diff --git a/Practice/test/human.java b/Practice/test/human.java new file mode 100644 index 0000000..591d6e1 --- /dev/null +++ b/Practice/test/human.java @@ -0,0 +1,33 @@ +package Practice.test; + +public class human { + private String name; + + public human(String name){ + this.name = name; + } + + public String getName(){ + return this.name; + } +} + +class Student extends human{ + private int id; + + public Student(String Name, int id){ + super(Name); + this.id = id; + } + public int getId(){ + return this.id; + } + + public static void main (String[] args){ + Student st = new Student("John", 123); + System.out.println(st.getName()); + System.out.println(st.getId()); + + } + +} diff --git a/Practice/test2/ExceptionalCalculator.java b/Practice/test2/ExceptionalCalculator.java new file mode 100644 index 0000000..cb7328a --- /dev/null +++ b/Practice/test2/ExceptionalCalculator.java @@ -0,0 +1,67 @@ +package Practice.test2; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public class ExceptionalCalculator { + private double result, num1, num2; + + public ExceptionalCalculator(double num1, double num2){ + this.num1 = num1; + this.num2 = num2; + } + + public double add() throws IllegalArgumentException{ + if (num1 < 0 || num2 < 0){ + throw new IllegalArgumentException("Numbers cannot be negative"); + } + + return num1 + num2; + } + + public double div() throws ArithmeticException{ + if (num1 == 0 || num2 == 0){ + throw new ArithmeticException("Numbers cannot be zero"); + } + return num1 / num2; + } + + public String toString(){ + return "The numbers are " + num1 + " and " + num2 + " and the result is " + result + "."; + } + + public static void main(String[] args) { +// ExceptionalCalculator calc = new ExceptionalCalculator(5, 0); +// try { +// System.out.println(calc.add()); +// } catch (IllegalArgumentException e) { +// System.out.println(e.getMessage()); +// } +// +// try{ +// System.out.println(calc.div()); +// } +// catch (ArithmeticException e){ +// System.out.println(e.getMessage()); +// } +// finally{ +// System.out.println("Program ended"); +// System.out.print(calc); +// } + Scanner sc = new Scanner(System.in); + try{ + int num = sc.nextInt(); + if (num < 0){ + throw new Exception("Number cannot be negative"); + } + } + catch (Exception e){ + System.out.println(e.getMessage()); + } + finally{ + System.out.println("Program ended"); + } + } + + +} diff --git a/Practice/test3/findmax.java b/Practice/test3/findmax.java new file mode 100644 index 0000000..50123e0 --- /dev/null +++ b/Practice/test3/findmax.java @@ -0,0 +1,33 @@ +package Practice.test3; + +public class findmax { + // Get max value from array + public static int findMax(int[] arr){ + int max = 0; + for (int i = 1; i < arr.length; i++){ + if (arr[i] > arr[max]){ + max = i; + } + } + return max; + } + + +} + +class Counter{ + public Counter(int count) { + this.count = count; + } + private int count = 0; + public void increment(){ + count++; + } + public int getCount(){ + return count; + } + public int decrement(){ + return count--; + } + +} diff --git a/Practice/test3/findmaxTest.java b/Practice/test3/findmaxTest.java new file mode 100644 index 0000000..43e24ef --- /dev/null +++ b/Practice/test3/findmaxTest.java @@ -0,0 +1,30 @@ +package Practice.test3; + +import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.Assert.*; + +class findmaxTest { + +// @Test +// void findMaxFromArray() { +// int[] arr = {1,2,3,4,5}; +// assertEquals(4, findmax.findMax(arr)); +// } + Counter c = null; + @Before + public void setUp(){ + System.out.println("Before"); + c = new Counter(0); + } + + @Test + public void testIncrement(){ + //Counter c = new Counter(); + c.increment(); + assertEquals(1, c.getCount()); + } +} \ No newline at end of file diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..15225e8 --- /dev/null +++ b/README.MD @@ -0,0 +1,3 @@ +# CSC 1109 Labs + +This is a collection of my labs and submissions for future references. diff --git a/Week10_Lab/Submission/CSC1109_Lab11_2200624.pdf b/Week10_Lab/Submission/CSC1109_Lab11_2200624.pdf new file mode 100644 index 0000000..ac78cc3 Binary files /dev/null and b/Week10_Lab/Submission/CSC1109_Lab11_2200624.pdf differ diff --git a/Week10_Lab/Submission/CSC1109_Lab11_2200624.tex b/Week10_Lab/Submission/CSC1109_Lab11_2200624.tex new file mode 100644 index 0000000..6c6e398 --- /dev/null +++ b/Week10_Lab/Submission/CSC1109_Lab11_2200624.tex @@ -0,0 +1,165 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + +% Image path +\graphicspath{{images/}} + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 11} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=python, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 11} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +\begin{lstlisting}[label={list:calculator},caption=calculator.py] +class calculator: + def __init__(self, x, y): + self.x = x + self.y = y + + def adder(self): + print("The sum is: " + str(self.x + self.y)) + return self.x + self.y + + def subtractor(self): + print("The difference is: " + str(self.x - self.y)) + return self.x - self.y + + def multiplier(self): + print("The multiplication is: " + str(self.x * self.y)) + return self.x * self.y + + def divider(self): + print("The quotient is: " + str(self.x / self.y)) + return self.x / self.y + + def clear(self): + self.x = 0 + self.y = 0 + print("Numbers are reset to be zero") + return self.x, self.y + + +if __name__ == "__main__": + x = int(input("Enter the first number: ")) + y = int(input("Enter the second number: ")) + calc = calculator(x, y) + calc.adder() + calc.subtractor() + calc.multiplier() + calc.divider() + calc.clear() +\end{lstlisting} +\begin{lstlisting}[label={list:calculator_output},caption=calculator.py output] +# Output 1 +Enter the first number: 10 +Enter the second number: 5 +The sum is: 15 +The difference is: 5 +The multiplication is: 50 +The quotient is: 2.0 +Numbers are reset to be zero + +# Output 2 +Enter the first number: 100 +Enter the second number: 5 +The sum is: 105 +The difference is: 95 +The multiplication is: 500 +The quotient is: 20.0 +Numbers are reset to be zero +\end{lstlisting} + + +\end{document} diff --git a/Week10_Lab/calculator.java b/Week10_Lab/calculator.java new file mode 100644 index 0000000..2f1ee3d --- /dev/null +++ b/Week10_Lab/calculator.java @@ -0,0 +1,89 @@ +package Week10_Lab; + +import java.util.Scanner; + +public class calculator { + private int input1; + private int input2; + private int result; + public calculator(int input1, int input2){ + this.input1 = input1; + this.input2 = input2; + } + public calculator(){ + this(0,0); + } + public int addr(int input1, int input2){ + this.result = input1 + input2; + return this.result; + } + public int subtractor(int input1, int input2){ + this.result = input1 - input2; + return this.result; + } + public int multiplier(int input1, int input2){ + this.result = input1 * input2; + return this.result; + } + public int divider(int input1, int input2){ + this.result = input1 / input2; + return this.result; + } + public void clear(){ + this.result = 0; + } + + public static void main(String[] args) { + calculator c = new calculator(); + Scanner sc = new Scanner(System.in); + + do { + System.out.println("Enter 1 for addition"); + System.out.println("Enter 2 for subtraction"); + System.out.println("Enter 3 for multiplication"); + System.out.println("Enter 4 for division"); + System.out.println("Enter 5 to clear"); + System.out.println("Enter 6 to exit"); + System.out.println("Enter your choice: "); + int choice = sc.nextInt(); + + switch (choice) { + case 1: + System.out.println("Enter the first number: "); + int input1 = sc.nextInt(); + System.out.println("Enter the second number: "); + int input2 = sc.nextInt(); + System.out.println("The Addition of " + input1 + " and " + input2 + " is " + c.addr(input1, input2)); + break; + case 2: + System.out.println("Enter the first number: "); + input1 = sc.nextInt(); + System.out.println("Enter the second number: "); + input2 = sc.nextInt(); + System.out.println("The Subtraction of " + input1 + " and " + input2 + " is " + c.subtractor(input1, input2)); + break; + case 3: + System.out.println("Enter the first number: "); + input1 = sc.nextInt(); + System.out.println("Enter the second number: "); + input2 = sc.nextInt(); + System.out.println("The Multiplication of " + input1 + " and " + input2 + " is " + c.multiplier(input1, input2)); + break; + case 4: + System.out.println("Enter the first number: "); + input1 = sc.nextInt(); + System.out.println("Enter the second number: "); + input2 = sc.nextInt(); + System.out.println("The Division of " + input1 + " and " + input2 + " is " + c.divider(input1, input2)); + break; + case 5: + c.clear(); + System.out.println("The result is cleared"); + break; + default: + System.out.println("Invalid choice"); + break; + } + } while (true); + } +} diff --git a/Week10_Lab/calculator.py b/Week10_Lab/calculator.py new file mode 100644 index 0000000..48300f6 --- /dev/null +++ b/Week10_Lab/calculator.py @@ -0,0 +1,37 @@ +class calculator: + def __init__(self, x, y): + self.x = x + self.y = y + + def adder(self): + print("The sum is: " + str(self.x + self.y)) + return self.x + self.y + + def subtractor(self): + print("The difference is: " + str(self.x - self.y)) + return self.x - self.y + + def multiplier(self): + print("The multiplication is: " + str(self.x * self.y)) + return self.x * self.y + + def divider(self): + print("The quotient is: " + str(self.x / self.y)) + return self.x / self.y + + def clear(self): + self.x = 0 + self.y = 0 + print("Numbers are reset to be zero") + return self.x, self.y + + +if __name__ == "__main__": + x = int(input("Enter the first number: ")) + y = int(input("Enter the second number: ")) + calc = calculator(x, y) + calc.adder() + calc.subtractor() + calc.multiplier() + calc.divider() + calc.clear() \ No newline at end of file diff --git a/Week1_Lab/Readme.md b/Week1_Lab/Readme.md new file mode 100644 index 0000000..04de651 --- /dev/null +++ b/Week1_Lab/Readme.md @@ -0,0 +1,7 @@ +## Question 1 +> Which version of the Java SDK did you install? + +openjdk-19.0.1 + +## Question 2 +Source code in the folder `src/Week1_Lab` diff --git a/Week1_Lab/Submission/CSC1109_Lab1_2200624.pdf b/Week1_Lab/Submission/CSC1109_Lab1_2200624.pdf new file mode 100644 index 0000000..03fbf3c Binary files /dev/null and b/Week1_Lab/Submission/CSC1109_Lab1_2200624.pdf differ diff --git a/Week1_Lab/Submission/CSC1109_Lab1_2200624.tex b/Week1_Lab/Submission/CSC1109_Lab1_2200624.tex new file mode 100644 index 0000000..d6b9e11 --- /dev/null +++ b/Week1_Lab/Submission/CSC1109_Lab1_2200624.tex @@ -0,0 +1,206 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 1} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 1} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +Which version of the Java SDK did you install? +\\ +I installed `openjdk-19.0.1` with Intellij. + +\section*{Question 2} +With reference to the lecture slides (Week 1), Java Program Structure Examples, modify: +\subsection*{Part A} + +Example 1, print out console message with “Hello, I am [your name]!”. + +\begin{lstlisting}[label={list:first},caption=Part A Source Code.] +public class parta { + public static void main(String[] args) { + System.out.println("Hello, I am Jun Wei"); + } +} + +\end{lstlisting} + +\begin{lstlisting}[label={list:first_output},caption=Part A Output.] +Hello, I am Jun Wei +\end{lstlisting} + +\pagebreak + +\subsection*{Part B} +Example 3, change the currency variable into the module code you are taking in this trimester, while the switch case will print out the complete module title. E.g.: input CSC1009 > Output “Object-Oriented Programming” +\begin{lstlisting}[label={list:second},caption=Part B Source code.] +import java.util.Scanner; + +public class partb { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.println("Enter module code: "); + String module = sc.nextLine(); + + switch(module){ + case "CSC1109": + System.out.println("Object-Oriented Programming"); + break; + case "CSC1108": + System.out.println("Data Structures and Algorithms"); + break; + case "INF1006": + System.out.println("Computer Networks"); + break; + case "INF1004": + System.out.println("Mathematics 2"); + break; + default: + System.out.println("Invalid module code"); + break; + } + } + +} +\end{lstlisting} + +\begin{lstlisting}[label={list:second_output},caption=Part B Output.] +Enter module code: +CSC1109 +Object-Oriented Programming +\end{lstlisting} + +\pagebreak +\subsection*{Part C} + +Example 4: change the for loop, print out the odd number in descending order starting from 102 and ending with 66 + +\begin{lstlisting}[label={list:third},caption=Part C Source Code.] +public class partc { + public static void main(String[] args) { + for(int i = 102; i >= 66; i--){ + if(i % 2 == 1){ + System.out.println(i); + } + } + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:third_output},caption=Part C Output.] + 101 + 99 + 97 + 95 + 93 + 91 + 89 + 87 + 85 + 83 + 81 + 79 + 77 + 75 + 73 + 71 + 69 + 67 +\end{lstlisting} + +\end{document} \ No newline at end of file diff --git a/Week1_Lab/parta.java b/Week1_Lab/parta.java new file mode 100644 index 0000000..bf2ca31 --- /dev/null +++ b/Week1_Lab/parta.java @@ -0,0 +1,7 @@ +package Week1_Lab; + +public class parta { + public static void main(String[] args) { + System.out.println("Hello, I am Jun Wei"); + } +} diff --git a/Week1_Lab/partb.java b/Week1_Lab/partb.java new file mode 100644 index 0000000..ee3c849 --- /dev/null +++ b/Week1_Lab/partb.java @@ -0,0 +1,31 @@ +package Week1_Lab; + +import java.util.Scanner; + +public class partb { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.println("Enter module code: "); + String module = sc.nextLine(); + + switch(module){ + case "CSC1109": + System.out.println("Object-Oriented Programming"); + break; + case "CSC1108": + System.out.println("Data Structures and Algorithms"); + break; + case "INF1006": + System.out.println("Computer Networks"); + break; + case "INF1004": + System.out.println("Mathematics 2"); + break; + default: + System.out.println("Invalid module code"); + break; + } + } + +} diff --git a/Week1_Lab/partc.java b/Week1_Lab/partc.java new file mode 100644 index 0000000..c6a4a6f --- /dev/null +++ b/Week1_Lab/partc.java @@ -0,0 +1,11 @@ +package Week1_Lab; + +public class partc { + public static void main(String[] args) { + for(int i = 102; i >= 66; i--){ + if(i % 2 == 1){ + System.out.println(i); + } + } + } +} diff --git a/Week2_Lab/Submission/CSC1109_Lab2_2200624.pdf b/Week2_Lab/Submission/CSC1109_Lab2_2200624.pdf new file mode 100644 index 0000000..8301cf9 Binary files /dev/null and b/Week2_Lab/Submission/CSC1109_Lab2_2200624.pdf differ diff --git a/Week2_Lab/Submission/CSC1109_Lab2_2200624.tex b/Week2_Lab/Submission/CSC1109_Lab2_2200624.tex new file mode 100644 index 0000000..6169989 --- /dev/null +++ b/Week2_Lab/Submission/CSC1109_Lab2_2200624.tex @@ -0,0 +1,272 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 2} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 2} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +Develop a program to accept the radius of one circle from the console and output +the area of the circle. Note that to compute the area, the following formula can be used: Area = radius * radius * PI +Define PI as a constant variable with a fixed value 3.14159 + +\begin{lstlisting}[label={list:first},caption=Question 1 Source Code.] +import java.util.*; + +public class q1 { + static final double PI = 3.14159; + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter a number for radius: "); + double radius = sc.nextDouble(); + double area = PI * radius * radius; + System.out.println("The area for the circle of radius " + radius + " is " + area); + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:first_output},caption=Question 1 Output.] +Enter a number for radius: 2.5 +The area for the circle of radius 2.5 is 19.6349375 + +Enter a number for radius: 23 +The area for the circle of radius 23.0 is 1661.90111 + +Enter a number for radius: 7.3 +The area for the circle of radius 7.3 is 167.41533109999997 +\end{lstlisting} + +\pagebreak + +\section*{Question 2} +Average calculation for multiple input from keyboard: In this question, you will design a program to accept three number inputs by the user, and display the average of it. + +\begin{lstlisting}[label={list:second},caption=Question 2 Source code.] +import java.util.*; + +public class q1 { + static final double PI = 3.14159; + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter a number for radius: "); + double radius = sc.nextDouble(); + double area = PI * radius * radius; + System.out.println("The area for the circle of radius " + radius + " is " + area); + + } +} + +\end{lstlisting} + +\begin{lstlisting}[label={list:second_output},caption=Question 2 Output.] +Enter three numbers:10.5 +11 +11.5 +The average of 10.5 11.0 11.5 is 11.0 + +Enter three numbers:1 2 3 +The average of 1.0 2.0 3.0 is 2.0 + +Enter three numbers:10 +11.5 19 +The average of 10.0 11.5 19.0 is 13.5 + +\end{lstlisting} + +\pagebreak + +\section*{Question 3} + +\begin{lstlisting}[label={list:third},caption=Question 3 Source Code.] +public class q3 { + public static void main(String[] args) { + long totalMilliseconds = System.currentTimeMillis(); + long totalSeconds = totalMilliseconds/1000; + long currSecond = totalSeconds % 60; + long totalMinutes = totalSeconds / 60; + long currMinute = totalMinutes % 60; + long totalHours = totalMinutes / 60; + long currrHour = totalHours % 24; + + System.out.println("Current time is " + currrHour + ":" + currMinute + ":" + currSecond + " GMT"); + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:third_output},caption=Question 3 Output.] +Current time is 6:49:27 GMT +\end{lstlisting} + +\pagebreak + +\section*{Question 4} +Chinese Zodiac Calculation: Now let us write a program to find out the Chinese Zodiac sign for +a given year. The Chinese Zodiac is based on a twelve-year cycle, with each year represented +by an animal- monkey, rooster, dog, pig, rat, ox, tiger, rabbit, dragon, snake, horse, or sheep— +in this cycle, as shown in Figure 2. +\\ +Note that year \% 12 determines the Zodiac sign. 1900 is the year of the rat because 1900 \% +12 is 4. Listing 3.9 gives a program that prompts the user to enter a year and displays the + +\begin{lstlisting}[label={list:fourth},caption=Question 4 Source Code.] +import java.util.*; + +public class q4 { + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + + System.out.print("Enter a year: "); + int year = sc.nextInt(); + + switch(year % 12){ + case 0: + System.out.println("monkey"); + break; + case 1: + System.out.println("rooster"); + break; + case 2: + System.out.println("dog"); + break; + case 3: + System.out.println("pig"); + break; + case 4: + System.out.println("rat"); + break; + case 5: + System.out.println("ox"); + break; + case 6: + System.out.println("tiger"); + break; + case 7: + System.out.println("rabbit"); + break; + case 8: + System.out.println("dragon"); + break; + case 9: + System.out.println("snake"); + break; + case 10: + System.out.println("horse"); + break; + case 11: + System.out.println("sheep"); + break; + default: + System.out.println("Invalid input"); + break; + } + } +} + +\end{lstlisting} + +\begin{lstlisting}[label={list:fourth_output},caption=Question 4 Output.] +Enter a year: 1963 +rabbit + +Enter a year: 1877 +ox + +Enter a year: 2000 +dragon +\end{lstlisting} + +\end{document} diff --git a/Week2_Lab/q1.java b/Week2_Lab/q1.java new file mode 100644 index 0000000..1317fa2 --- /dev/null +++ b/Week2_Lab/q1.java @@ -0,0 +1,16 @@ +package Week2_Lab; + +import java.util.*; + +public class q1 { + + static final double PI = 3.14159; + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("Enter a number for radius: "); + double radius = sc.nextDouble(); + double area = PI * radius * radius; + System.out.println("The area for the circle of radius " + radius + " is " + area); + + } +} diff --git a/Week2_Lab/q2.java b/Week2_Lab/q2.java new file mode 100644 index 0000000..b7ca9ec --- /dev/null +++ b/Week2_Lab/q2.java @@ -0,0 +1,19 @@ +package Week2_Lab; + +import java.util.*; + +public class q2 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.print("Enter three numbers:"); + double num1 = sc.nextDouble(); + double num2 = sc.nextDouble(); + double num3 = sc.nextDouble(); + + double average = (num1 + num2 + num3) / 3; + + System.out.println("The average of " + num1 + " " + num2 + " " + num3 + " is " + average); + + } +} diff --git a/Week2_Lab/q3.java b/Week2_Lab/q3.java new file mode 100644 index 0000000..ed205d4 --- /dev/null +++ b/Week2_Lab/q3.java @@ -0,0 +1,15 @@ +package Week2_Lab; + +public class q3 { + public static void main(String[] args) { + long totalMilliseconds = System.currentTimeMillis(); + long totalSeconds = totalMilliseconds/1000; + long currSecond = totalSeconds % 60; + long totalMinutes = totalSeconds / 60; + long currMinute = totalMinutes % 60; + long totalHours = totalMinutes / 60; + long currrHour = totalHours % 24; + + System.out.println("Current time is " + currrHour + ":" + currMinute + ":" + currSecond + " GMT"); + } +} diff --git a/Week2_Lab/q4.java b/Week2_Lab/q4.java new file mode 100644 index 0000000..e5a7b80 --- /dev/null +++ b/Week2_Lab/q4.java @@ -0,0 +1,54 @@ +package Week2_Lab; + +import java.util.*; + +public class q4 { + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + + System.out.print("Enter a year: "); + int year = sc.nextInt(); + + switch(year % 12){ + case 0: + System.out.println("monkey"); + break; + case 1: + System.out.println("rooster"); + break; + case 2: + System.out.println("dog"); + break; + case 3: + System.out.println("pig"); + break; + case 4: + System.out.println("rat"); + break; + case 5: + System.out.println("ox"); + break; + case 6: + System.out.println("tiger"); + break; + case 7: + System.out.println("rabbit"); + break; + case 8: + System.out.println("dragon"); + break; + case 9: + System.out.println("snake"); + break; + case 10: + System.out.println("horse"); + break; + case 11: + System.out.println("sheep"); + break; + default: + System.out.println("Invalid input"); + break; + } + } +} diff --git a/Week3_Lab/Submission/CSC1109_Lab3_2200624.pdf b/Week3_Lab/Submission/CSC1109_Lab3_2200624.pdf new file mode 100644 index 0000000..61761b3 Binary files /dev/null and b/Week3_Lab/Submission/CSC1109_Lab3_2200624.pdf differ diff --git a/Week3_Lab/Submission/CSC1109_Lab3_2200624.tex b/Week3_Lab/Submission/CSC1109_Lab3_2200624.tex new file mode 100644 index 0000000..a910d19 --- /dev/null +++ b/Week3_Lab/Submission/CSC1109_Lab3_2200624.tex @@ -0,0 +1,207 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 3} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 3} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} + +\begin{lstlisting}[label={list:first},caption=Question 1 Source Code.] +import java.util.*; + +public class loan { + private double annualInterestRate; + private int numberOfYears; + private double loanAmount; + private java.util.Date loanDate; + + public loan(){ + this.annualInterestRate = 2.5; + this.numberOfYears = 1; + this.loanAmount = 1000; + loanDate = new java.util.Date(); + } + public loan(double annualInterestRate, int numberOfYears, double loanAmount){ + this.annualInterestRate = annualInterestRate; + this.numberOfYears = numberOfYears; + this.loanAmount = loanAmount; + loanDate = new java.util.Date(); + } + + public double getAnnualInterestRate(){ + return this.annualInterestRate; + } + + public int getNumberOfYears(){ + return this.numberOfYears; + } + + public double getLoanAmount(){ + return this.loanAmount; + } + + public java.util.Date getLoanDate(){ + return this.loanDate; + } + + public void setAnnualInterestRate(double annualInterestRate){ + this.annualInterestRate = annualInterestRate; + } + + public void setNumberOfYears(int numberOfYears){ + this.numberOfYears = numberOfYears; + } + + public void setLoadAmount(double loanAmount){ + this.loanAmount = loanAmount; + } + + public double getMonthlyPayment(){ + double monthlyInterestRate = annualInterestRate / 1200; + double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12))); + return monthlyPayment; + } + public double getTotalPayment(){ + double totalPayment = getMonthlyPayment() * numberOfYears * 12; + return totalPayment; + } + + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + + // Annual Interest + System.out.print("Enter annual interest rate, for example, 8.25: "); + double annualInterestRate = sc.nextDouble(); + + // Number of years + System.out.print("Enter number of years as an integer: "); + int numberOfYears = sc.nextInt(); + + // Loan Amount + System.out.print("Enter loan amount, for example, 120000.95: "); + double loanAmount = sc.nextDouble(); + + // Create a Loan object + loan loan1 = new loan(annualInterestRate, numberOfYears, loanAmount); + + // Date + java.util.Date loanDate = loan1.getLoanDate(); + System.out.println("The loan was created on " + loanDate); + + // Monthly payment + double monthlyPayment = loan1.getMonthlyPayment(); + System.out.printf("The monthly payment is %.2f\n", monthlyPayment); + + // Total Payment + double totalPayment = loan1.getTotalPayment(); + System.out.printf("The total payment is %.2f", totalPayment); + + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:first_output},caption=Question 1 Output.] +Enter annual interest rate, for example, 8.25: 2.5 +Enter number of years as an integer: 5 +Enter loan amount, for example, 120000.95: 1000 +The loan was created on Mon Jan 09 15:31:09 SGT 2023 +The monthly payment is 17.75 +The total payment is 1064.84 +\end{lstlisting} + +\end{document} diff --git a/Week3_Lab/loan.java b/Week3_Lab/loan.java new file mode 100644 index 0000000..83045d4 --- /dev/null +++ b/Week3_Lab/loan.java @@ -0,0 +1,95 @@ +package Week3_Lab; + +import java.util.*; + +public class loan { + private double annualInterestRate; + private int numberOfYears; + private double loanAmount; + private java.util.Date loanDate; + + public loan(){ + //this.annualInterestRate = 2.5; + //this.numberOfYears = 1; + //this.loanAmount = 1000; + this(2.5, 1, 1000); + loanDate = new java.util.Date(); + } + public loan(double annualInterestRate, int numberOfYears, double loanAmount){ + this.annualInterestRate = annualInterestRate; + this.numberOfYears = numberOfYears; + this.loanAmount = loanAmount; + loanDate = new java.util.Date(); + } + + public double getAnnualInterestRate(){ + return this.annualInterestRate; + } + + public int getNumberOfYears(){ + return this.numberOfYears; + } + + public double getLoanAmount(){ + return this.loanAmount; + } + + public java.util.Date getLoanDate(){ + return this.loanDate; + } + + public void setAnnualInterestRate(double annualInterestRate){ + this.annualInterestRate = annualInterestRate; + } + + public void setNumberOfYears(int numberOfYears){ + this.numberOfYears = numberOfYears; + } + + public void setLoadAmount(double loanAmount){ + this.loanAmount = loanAmount; + } + + public double getMonthlyPayment(){ + double monthlyInterestRate = annualInterestRate / 1200; + double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12))); + return monthlyPayment; + } + public double getTotalPayment(){ + double totalPayment = getMonthlyPayment() * numberOfYears * 12; + return totalPayment; + } + + public static void main(String[] args){ + Scanner sc = new Scanner(System.in); + + // Annual Interest + System.out.print("Enter annual interest rate, for example, 8.25: "); + double annualInterestRate = sc.nextDouble(); + + // Number of years + System.out.print("Enter number of years as an integer: "); + int numberOfYears = sc.nextInt(); + + // Loan Amount + System.out.print("Enter loan amount, for example, 120000.95: "); + double loanAmount = sc.nextDouble(); + + // Create a Loan object + loan loan1 = new loan(annualInterestRate, numberOfYears, loanAmount); + + // Date + java.util.Date loanDate = loan1.getLoanDate(); + System.out.println("The loan was created on " + loanDate); + + + // Monthly payment + double monthlyPayment = loan1.getMonthlyPayment(); + System.out.printf("The monthly payment is %.2f\n", monthlyPayment); + + // Total Payment + double totalPayment = loan1.getTotalPayment(); + System.out.printf("The total payment is %.2f", totalPayment); + + } +} diff --git a/Week4_Lab/BMI.java b/Week4_Lab/BMI.java new file mode 100644 index 0000000..4b483b2 --- /dev/null +++ b/Week4_Lab/BMI.java @@ -0,0 +1,49 @@ +package Week4_Lab; + + +public class BMI { + + private double heightInInches; + private double weightInPounds; + private double bmi; + public BMI(double heightInInches, double weightInPounds){ + this.heightInInches = heightInInches; + this.weightInPounds = weightInPounds; + } + + public double getHeightInInches() { + return this.heightInInches; + } + + public double getWeightInPounds() { + return this.weightInPounds; + } + public void setHeightInInches(double heightInInches) { + this.heightInInches = heightInInches; + } + + public void setWeightInPounds(double weightInPounds) { + this.weightInPounds = weightInPounds; + } + + public double calBMI(double heightInInches, double weightInPounds){ + double heightInMeters = heightInInches * 0.0254; + double weightInKilograms = weightInPounds * 0.45359237; + this.bmi = weightInKilograms / (heightInMeters * heightInMeters); + return this.bmi; + } + + public void BMIInterpretation() { + if (this.bmi < 18.5) { + System.out.println("Underweight"); + } else if (this.bmi >= 18.5 && this.bmi < 25) { + System.out.println("Normal"); + } else if (this.bmi >= 25 && this.bmi < 30) { + System.out.println("Overweight"); + } else if (this.bmi >= 30) { + System.out.println("Obese"); + } + } + + +} diff --git a/Week4_Lab/BMI_Main.java b/Week4_Lab/BMI_Main.java new file mode 100644 index 0000000..24b69c3 --- /dev/null +++ b/Week4_Lab/BMI_Main.java @@ -0,0 +1,21 @@ +package Week4_Lab; + +import java.util.Scanner; + +public class BMI_Main { + public static void main(String[] args) { + + Scanner s = new Scanner(System.in); + + System.out.print("Enter your weight in pounds: "); + double weightInPounds = s.nextFloat(); + + System.out.print("Enter your height in inches: "); + double heightInInches = s.nextFloat(); + + BMI bmi = new BMI(heightInInches, weightInPounds); + System.out.println("BMI is " + bmi.calBMI(bmi.getHeightInInches(), bmi.getWeightInPounds())); + + bmi.BMIInterpretation(); + } +} diff --git a/Week4_Lab/StackOfIntegers.java b/Week4_Lab/StackOfIntegers.java new file mode 100644 index 0000000..73b5c63 --- /dev/null +++ b/Week4_Lab/StackOfIntegers.java @@ -0,0 +1,35 @@ +package Week4_Lab; + +public class StackOfIntegers { + private int[] elements; + private int size; + + public StackOfIntegers(){ + this(16); + } + public StackOfIntegers(int capacity){ + this.elements = new int[capacity]; + this.size = -1; + } + + public boolean empty(){ + return size == -1; + } + public int peek(){ + return elements[size - 1]; + } + + public void push(int value){ + this.size++; + this.elements[size] = value; + } + public int pop(){ + int value = elements[size]; + this.size--; + return value; + } + public int getSize(){ + return size + 1; + } +} + diff --git a/Week4_Lab/Submission/CSC1109_Lab4_2200624.pdf b/Week4_Lab/Submission/CSC1109_Lab4_2200624.pdf new file mode 100644 index 0000000..40fa97c Binary files /dev/null and b/Week4_Lab/Submission/CSC1109_Lab4_2200624.pdf differ diff --git a/Week4_Lab/Submission/CSC1109_Lab4_2200624.tex b/Week4_Lab/Submission/CSC1109_Lab4_2200624.tex new file mode 100644 index 0000000..0bd7c57 --- /dev/null +++ b/Week4_Lab/Submission/CSC1109_Lab4_2200624.tex @@ -0,0 +1,284 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 4} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 4} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} + +\textbf{Method assignments} + +I first instantiated 3 variables: `heightInInches`, `weightInPounds` and `bmi`. +The constructor takes in 2 parameters, `heightInInches` and `weightInPounds` +and assigns them to the corresponding variables.\\ + +The getters and setters are required to access the variables from outside the class, +which was required for the `main` method in BMI\_Main.java.\\ +\\ +\textbf{calBMI()} + +The `calBMI` method takes in 2 parameters, `heightInInches` and `weightInPounds`. +Using these variables, I first converted the \textbf{height} from inches to meters, +using the formula `heightInMeters = heightInInches * 0.0254` where 0.0254 is given as the conversion ratio in the lab handout and +I converted the \textbf{weight} from pounds to kilograms, using the formula `weightInKilograms = weightInPounds * 0.45359237` where 0.45359237 is given as the conversion ratio in the lab handout. + +I then calculated the \textbf{BMI} using the formula `bmi = weightInKilograms / (heightInMeters * heightInMeters)`.\\ +\\ +\textbf{BMIInterpretation()} + +The `BMIInterpretation` method takes in 1 parameter, `bmi` and returns a string +based on the value of `bmi`.\\ +The method checks against values in the table provided in the lab sheet and returns the corresponding string.\\ + +\pagebreak +\begin{lstlisting}[label={list:BMI},caption=BMI.java] +public class BMI { + private double heightInInches; + private double weightInPounds; + private double bmi; + + public BMI(double heightInInches, double weightInPounds){ + this.heightInInches = heightInInches; + this.weightInPounds = weightInPounds; + } + + public double getHeightInInches() { + return this.heightInInches; + } + + public double getWeightInPounds() { + return this.weightInPounds; + } + public void setHeightInInches(double heightInInches) { + this.heightInInches = heightInInches; + } + + public void setWeightInPounds(double weightInPounds) { + this.weightInPounds = weightInPounds; + } + + public double calBMI(double heightInInches, double weightInPounds){ + double heightInMeters = heightInInches * 0.0254; + double weightInKilograms = weightInPounds * 0.45359237; + this.bmi = weightInKilograms / (heightInMeters * heightInMeters); + return this.bmi; + } + + public void BMIInterpretation() { + if (this.bmi < 18.5) { + System.out.println("Underweight"); + } else if (this.bmi >= 18.5 && this.bmi < 25) { + System.out.println("Normal"); + } else if (this.bmi >= 25 && this.bmi < 30) { + System.out.println("Overweight"); + } else if (this.bmi >= 30) { + System.out.println("Obese"); + } + } +} +\end{lstlisting} +\pagebreak + +\textbf{BMI\_Main.java} + +The `BMI\_Main` class uses the `BMI` class to calculate the BMI of a person. This is +the main function that was used to access an use the `BMI` class.\\ +Using a Scanner, I first got the hight and weight from the user, +I then created a new `BMI` object and passed the height and weight to the constructor. +I called the `calBMI` method and passed the height and weight to the method.\\ + +Lastly, the `BMIInterpretation` method was called to print the BMI interpretation. +The input and output variables from the first output corresponds with the output from the lab sheet\\ + +\begin{lstlisting}[label={list:BMI_Main},caption=BMI\_Main.java] +import java.util.Scanner; + +public class BMI_Main { + public static void main(String[] args) { + + Scanner s = new Scanner(System.in); + + System.out.print("Enter your weight in pounds: "); + double weightInPounds = s.nextFloat(); + + System.out.print("Enter your height in inches: "); + double heightInInches = s.nextFloat(); + + BMI bmi = new BMI(heightInInches, weightInPounds); + System.out.println("BMI is " + bmi.calBMI(bmi.getHeightInInches(), bmi.getWeightInPounds())); + + bmi.BMIInterpretation(); + } +} +\end{lstlisting} +\begin{lstlisting}[label={list:BMI_Output},caption=BMI\_Main.java Output] +//Output 1 +Enter your weight in pounds: 146 +Enter your height in inches: 70 +BMI is 20.948603801493316 +Normal + +//Output 2 +Enter your weight in pounds: 150 +Enter your height in inches: 80 +BMI is 16.478193272792794 +Underweight +\end{lstlisting} + +\pagebreak + +\section*{Question 2} + +\begin{lstlisting}[label={list:StackOfIntegers},caption=StackOfIntegers.java] + +public class StackOfIntegers { + private int[] elements; + private int size; + + public StackOfIntegers(){ + this.elements = new int[16]; + this.size = -1; + } + public StackOfIntegers(int capacity){ + this.elements = new int[capacity]; + this.size = -1; + } + + public boolean empty(){ + return size == -1; + } + public int peek(){ + return elements[size - 1]; + } + + public void push(int value){ + this.size++; + this.elements[size] = value; + } + public int pop(){ + int value = elements[size]; + this.size--; + return value; + } + public int getSize(){ + return size; + } +} +\end{lstlisting} + +\pagebreak + +\begin{lstlisting}[label={list:TestStackOfIntegers},caption=TestStackOfIntegers.java] +public class TestStackOfIntegers { + public static void main(String[] args) { + StackOfIntegers stack = new StackOfIntegers(); + for (int i = 0; i < 10; i++) { + stack.push(i); + } + while (!stack.empty()) { + System.out.print(stack.pop() + " "); + } + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:StackOfIntegers},caption=TestStackOfIntegers.java Output] +9 8 7 6 5 4 3 2 1 0 +\end{lstlisting} + +\end{document} diff --git a/Week4_Lab/TestStackOfIntegers.java b/Week4_Lab/TestStackOfIntegers.java new file mode 100644 index 0000000..60ef3c3 --- /dev/null +++ b/Week4_Lab/TestStackOfIntegers.java @@ -0,0 +1,13 @@ +package Week4_Lab; + +public class TestStackOfIntegers { + public static void main(String[] args) { + StackOfIntegers stack = new StackOfIntegers(); + for (int i = 0; i < 10; i++) { + stack.push(i); + } + while (!stack.empty()) { + System.out.print(stack.pop() + " "); + } + } +} diff --git a/Week5_Lab/GeometricObject/CircleFromSimpleGeometricObject.java b/Week5_Lab/GeometricObject/CircleFromSimpleGeometricObject.java new file mode 100644 index 0000000..066776f --- /dev/null +++ b/Week5_Lab/GeometricObject/CircleFromSimpleGeometricObject.java @@ -0,0 +1,44 @@ +package Week5_Lab.GeometricObject; + +public class CircleFromSimpleGeometricObject extends GeometricObject{ + private double radius; + + public CircleFromSimpleGeometricObject(){ + super(); + } + + public CircleFromSimpleGeometricObject(double radius){ + super(); + this.radius = radius; + } + + public CircleFromSimpleGeometricObject(double radius, String color, boolean filled){ + super(); + this.radius = radius; + } + + public double getRadius() { + return this.radius; + } + + public void setRadius(double radius) { + this.radius = radius; + } + + public double getArea(){ + return Math.PI * Math.pow(this.radius, 2); + } + + public double getPerimeter(){ + return 2 * Math.PI * this.radius; + } + + public double getDiameter(){ + return 2 * this.radius; + } + + public void printCircle(){ + System.out.println("The color is " + getColor() + "\nThe area is " + getArea() + "\nthe diameter is " + getDiameter()); + } + +} diff --git a/Week5_Lab/GeometricObject/GeometricObject.java b/Week5_Lab/GeometricObject/GeometricObject.java new file mode 100644 index 0000000..830e4c1 --- /dev/null +++ b/Week5_Lab/GeometricObject/GeometricObject.java @@ -0,0 +1,44 @@ +package Week5_Lab.GeometricObject; + +public class GeometricObject { + private String color; + private boolean filled; + private java.util.Date dateCreated; + + public GeometricObject() { + //this.color = "white"; + //this.filled = false; + this("white", false); + this.dateCreated = new java.util.Date(); + } + + public GeometricObject(String color, boolean filled){ + this.color = color; + this.filled = filled; + this.dateCreated = new java.util.Date(); + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public boolean isFilled() { + return filled; + } + + public void setFilled(boolean filled) { + this.filled = filled; + } + + public java.util.Date getDateCreated() { + return dateCreated; + } + + public String toString(){ + return " created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled; + } +} diff --git a/Week5_Lab/GeometricObject/RectangleFromSimpleGeometricObject.java b/Week5_Lab/GeometricObject/RectangleFromSimpleGeometricObject.java new file mode 100644 index 0000000..c68bd2f --- /dev/null +++ b/Week5_Lab/GeometricObject/RectangleFromSimpleGeometricObject.java @@ -0,0 +1,44 @@ +package Week5_Lab.GeometricObject; + +public class RectangleFromSimpleGeometricObject extends GeometricObject{ + private double width; + private double height; + + public RectangleFromSimpleGeometricObject(){ + super(); + } + public RectangleFromSimpleGeometricObject(double width, double height){ + super(); + this.width = width; + this.height = height; + } + public RectangleFromSimpleGeometricObject(double width, double height, String color, boolean filled){ + super(color, filled); + this.width = width; + this.height = height; + } + + public double getWidth() { + return this.width; + } + + public void setWidth(double width) { + this.width = width; + } + + public double getHeight(){ + return this.height; + } + + public double setHeight(){ + return this.height; + } + + public double getArea(){ + return this.width * this.height; + } + + public double getPerimeter(){ + return 2 * (this.width + this.height); + } +} diff --git a/Week5_Lab/GeometricObject/TestCircleRectangle.java b/Week5_Lab/GeometricObject/TestCircleRectangle.java new file mode 100644 index 0000000..6146ec1 --- /dev/null +++ b/Week5_Lab/GeometricObject/TestCircleRectangle.java @@ -0,0 +1,17 @@ +package Week5_Lab.GeometricObject; + +public class TestCircleRectangle { + public static void main(String[] args){ + CircleFromSimpleGeometricObject circle = new CircleFromSimpleGeometricObject(1); + System.out.println("A circle " + circle.toString()); + System.out.println("The color is " + circle.getColor()); + System.out.println("The radius is " + circle.getRadius()); + System.out.println("The area is " + circle.getArea()); + System.out.println("The diameter is " + circle.getDiameter()); + + RectangleFromSimpleGeometricObject rectangle = new RectangleFromSimpleGeometricObject(2, 4); + System.out.println("A rectangle " + rectangle.toString()); + System.out.println("The area is " + rectangle.getArea()); + System.out.println("The perimeter is " + rectangle.getPerimeter()); + } +} diff --git a/Week5_Lab/Submission/CSC1109_Lab5_2200624.pdf b/Week5_Lab/Submission/CSC1109_Lab5_2200624.pdf new file mode 100644 index 0000000..0793663 Binary files /dev/null and b/Week5_Lab/Submission/CSC1109_Lab5_2200624.pdf differ diff --git a/Week5_Lab/Submission/CSC1109_Lab5_2200624.tex b/Week5_Lab/Submission/CSC1109_Lab5_2200624.tex new file mode 100644 index 0000000..1d98129 --- /dev/null +++ b/Week5_Lab/Submission/CSC1109_Lab5_2200624.tex @@ -0,0 +1,389 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 5} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 5} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +\begin{lstlisting}[label={list:GeometricObject},caption=GeometricObject.java] +public class GeometricObject { + private String color; + private boolean filled; + private java.util.Date dateCreated; + + public GeometricObject() { + this.color = "white"; + this.filled = false; + this.dateCreated = new java.util.Date(); + } + + public GeometricObject(String color, boolean filled){ + this.color = color; + this.filled = filled; + this.dateCreated = new java.util.Date(); + } + + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public boolean isFilled() { + return filled; + } + + public void setFilled(boolean filled) { + this.filled = filled; + } + + public java.util.Date getDateCreated() { + return dateCreated; + } + + public String toString(){ + return " created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled; + } +} + +\end{lstlisting} + +\begin{lstlisting}[label={list:CircleFromSimpleGeometricObject},caption=CircleFromSimpleGeometricObject.java] +public class CircleFromSimpleGeometricObject extends GeometricObject{ + private double radius; + + public CircleFromSimpleGeometricObject(){ + super(); + } + + public CircleFromSimpleGeometricObject(double radius){ + super(); + this.radius = radius; + } + + public CircleFromSimpleGeometricObject(double radius, String color, boolean filled){ + super(); + this.radius = radius; + } + + public double getRadius() { + return this.radius; + } + + public void setRadius(double radius) { + this.radius = radius; + } + + public double getArea(){ + return Math.PI * Math.pow(this.radius, 2); + } + + public double getPerimeter(){ + return 2 * Math.PI * this.radius; + } + + public double getDiameter(){ + return 2 * this.radius; + } + + public void printCircle(){ + System.out.println("The color is " + getColor() + "\nThe area is " + getArea() + "\nthe diameter is " + getDiameter()); + } +} +\end{lstlisting} +\begin{lstlisting}[label={list:RectangleFromSimpleGeometricObject},caption=RectangleFromSimpleGeometricObject.java] +public class RectangleFromSimpleGeometricObject extends GeometricObject{ + private double width; + private double height; + + public RectangleFromSimpleGeometricObject(){ + super(); + } + public RectangleFromSimpleGeometricObject(double width, double height){ + super(); + this.width = width; + this.height = height; + } + public RectangleFromSimpleGeometricObject(double width, double height, String color, boolean filled){ + super(color, filled); + this.width = width; + this.height = height; + } + + public double getWidth() { + return this.width; + } + + public void setWidth(double width) { + this.width = width; + } + + public double getHeight(){ + return this.height; + } + + public double setHeight(){ + return this.height; + } + + public double getArea(){ + return this.width * this.height; + } + + public double getPerimeter(){ + return 2 * (this.width + this.height); + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:TestCircleRectangle},caption=TestCircleRectangle.java] +public class TestCircleRectangle { + public static void main(String[] args){ + CircleFromSimpleGeometricObject circle = new CircleFromSimpleGeometricObject(1); + System.out.println("A circle " + circle.toString()); + System.out.println("The color is " + circle.getColor()); + System.out.println("The radius is " + circle.getRadius()); + System.out.println("The area is " + circle.getArea()); + System.out.println("The diameter is " + circle.getDiameter()); + + RectangleFromSimpleGeometricObject rectangle = new RectangleFromSimpleGeometricObject(2, 4); + System.out.println("A rectangle " + rectangle.toString()); + System.out.println("The area is " + rectangle.getArea()); + System.out.println("The perimeter is " + rectangle.getPerimeter()); + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:TestCircleRectangle},caption=TestCircleRectangle.java] +A circle created on Fri Jan 27 15:07:16 SGT 2023 +color: white and filled: false +The color is white +The radius is 1.0 +The area is 3.141592653589793 +The diameter is 2.0 +A rectangle created on Fri Jan 27 15:07:16 SGT 2023 +color: white and filled: false +The area is 8.0 +The perimeter is 12.0 +\end{lstlisting} + + +\section*{Question 2} + +\begin{lstlisting}[label={list:Shape},caption=Shape.java] +public abstract class Shape { + public float dim1; + public float dim2; + public float PI = 3.14f; + + public Shape(float dim1, float dim2) { + this.dim1 = dim1; + this.dim2 = dim2; + } + + public abstract float area(); +} +\end{lstlisting} + +\begin{lstlisting}[label={list:Circle},caption=Circle.java] +public class Circle extends Shape{ + + public Circle(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim1 * PI; + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:Ellipse},caption=Ellipse.java] +public class Ellipse extends Shape{ + public Ellipse(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim2 * PI; + } +} +\end{lstlisting} +\pagebreak +\begin{lstlisting}[label={list:Rectangle},caption=Rectangle.java] +public class Rectangle extends Shape{ + + public Rectangle(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim2; + } + +} + +\end{lstlisting} +\begin{lstlisting}[label={list:Square},caption=Square.java] +public class Square extends Shape{ + + public Square(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim2; + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:Triangle},caption=Triangle.java] +public class Triangle extends Shape{ + + public Triangle(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return 0.5f * dim1 * dim2 ; + } +} + +\end{lstlisting} + +\pagebreak +\begin{lstlisting}[label={list:ShapeTest},caption=ShapeTest.java] +public class ShapeTest { + public static void main(String[] args){ + Rectangle r = new Rectangle(9,5); + Triangle t= new Triangle(10,8); + Circle c = new Circle(5,5); + Ellipse e = new Ellipse(7,7); + Square s = new Square(6,6); + Shape figref; + figref = r; + + System.out.println("Inside Area for Rectangle."); + System.out.println("Area is " + figref.area()); + figref = t; + System.out.println("Inside Area for Triangle."); + System.out.println("Area is " + figref.area()); + figref = c; + System.out.println("Inside Area for Circle."); + System.out.println("Area is " + figref.area()); + figref = e; + System.out.println("Inside Area for Ellipse."); + System.out.println("Area is " + figref.area()); + figref = s; + System.out.println("Inside Area for Square."); + System.out.println("Area is " + figref.area()); + + } +} + +\end{lstlisting} +\begin{lstlisting}[label={list:ShapeTestOutput},caption=ShapeTest.java Output] +Inside Area for Rectangle. +Area is 45.0 +Inside Area for Triangle. +Area is 40.0 +Inside Area for Circle. +Area is 78.5 +Inside Area for Ellipse. +Area is 153.86 +Inside Area for Square. +Area is 36.0 +\end{lstlisting} +\end{document} diff --git a/Week5_Lab/task2/Circle.java b/Week5_Lab/task2/Circle.java new file mode 100644 index 0000000..dfcc478 --- /dev/null +++ b/Week5_Lab/task2/Circle.java @@ -0,0 +1,11 @@ +package Week5_Lab.task2; + +public class Circle extends Shape{ + + public Circle(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim1 * PI; + } +} diff --git a/Week5_Lab/task2/Ellipse.java b/Week5_Lab/task2/Ellipse.java new file mode 100644 index 0000000..43b165b --- /dev/null +++ b/Week5_Lab/task2/Ellipse.java @@ -0,0 +1,11 @@ +package Week5_Lab.task2; + +public class Ellipse extends Shape{ + + public Ellipse(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim2 * PI; + } +} diff --git a/Week5_Lab/task2/Rectangle.java b/Week5_Lab/task2/Rectangle.java new file mode 100644 index 0000000..0a1abaa --- /dev/null +++ b/Week5_Lab/task2/Rectangle.java @@ -0,0 +1,12 @@ +package Week5_Lab.task2; + +public class Rectangle extends Shape{ + + public Rectangle(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim2; + } + +} diff --git a/Week5_Lab/task2/Shape.java b/Week5_Lab/task2/Shape.java new file mode 100644 index 0000000..d4f485d --- /dev/null +++ b/Week5_Lab/task2/Shape.java @@ -0,0 +1,16 @@ +package Week5_Lab.task2; + +public abstract class Shape { + + public float dim1; + public float dim2; + public float PI = 3.14f; + + public Shape(float dim1, float dim2) { + this.dim1 = dim1; + this.dim2 = dim2; + } + + public abstract float area(); + +} \ No newline at end of file diff --git a/Week5_Lab/task2/ShapeTest.java b/Week5_Lab/task2/ShapeTest.java new file mode 100644 index 0000000..e6ae9fa --- /dev/null +++ b/Week5_Lab/task2/ShapeTest.java @@ -0,0 +1,29 @@ +package Week5_Lab.task2; + +public class ShapeTest { + public static void main(String[] args){ + Rectangle r = new Rectangle(9,5); + Triangle t= new Triangle(10,8); + Circle c = new Circle(5,5); + Ellipse e = new Ellipse(7,7); + Square s = new Square(6,6); + Shape figref; + figref = r; + + System.out.println("Inside Area for Rectangle."); + System.out.println("Area is " + figref.area()); + figref = t; + System.out.println("Inside Area for Triangle."); + System.out.println("Area is " + figref.area()); + figref = c; + System.out.println("Inside Area for Circle."); + System.out.println("Area is " + figref.area()); + figref = e; + System.out.println("Inside Area for Ellipse."); + System.out.println("Area is " + figref.area()); + figref = s; + System.out.println("Inside Area for Square."); + System.out.println("Area is " + figref.area()); + + } +} diff --git a/Week5_Lab/task2/Square.java b/Week5_Lab/task2/Square.java new file mode 100644 index 0000000..dbd9d08 --- /dev/null +++ b/Week5_Lab/task2/Square.java @@ -0,0 +1,11 @@ +package Week5_Lab.task2; + +public class Square extends Shape{ + + public Square(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return dim1 * dim2; + } +} diff --git a/Week5_Lab/task2/Triangle.java b/Week5_Lab/task2/Triangle.java new file mode 100644 index 0000000..9809602 --- /dev/null +++ b/Week5_Lab/task2/Triangle.java @@ -0,0 +1,11 @@ +package Week5_Lab.task2; + +public class Triangle extends Shape{ + + public Triangle(float dim1, float dim2) { + super(dim1, dim2); + } + public float area() { + return 0.5f * dim1 * dim2 ; + } +} diff --git a/Week6_Lab/Submission/CSC1109_Lab6_2200624.pdf b/Week6_Lab/Submission/CSC1109_Lab6_2200624.pdf new file mode 100644 index 0000000..3639c84 Binary files /dev/null and b/Week6_Lab/Submission/CSC1109_Lab6_2200624.pdf differ diff --git a/Week6_Lab/Submission/CSC1109_Lab6_2200624.tex b/Week6_Lab/Submission/CSC1109_Lab6_2200624.tex new file mode 100644 index 0000000..16b52ed --- /dev/null +++ b/Week6_Lab/Submission/CSC1109_Lab6_2200624.tex @@ -0,0 +1,310 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 6} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 6} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +\begin{lstlisting}[label={list:GeometricObject},caption=LinkList.java] +import java.util.*; +public class lab6_LL { + + public static void main(String[] args){ + LinkedList ll = new LinkedList(); + + ll.add(1); + ll.add(3); + ll.add(5); + ll.add(7); + ll.add(9); + ll.add(11); + + // Question 1 + System.out.print("Before adding: "); + printLinkedList(ll); + System.out.print("After adding and sorting: "); + printLinkedList(addAndSort(ll, 10)); + + // Question 2 + //System.out.print("Before swapping:"); + //printLinkedList(ll); + System.out.print("After swapping:"); + swap(ll, 1, 6); + printLinkedList(ll); + + //Question 3 + LinkedList randInt = new LinkedList(); + Random rand = new Random(); + System.out.println("The 500 random numbers generated are: "); + for (int i = 0; i < 500; i++) { + randInt.add(rand.nextInt(1000, 9999)); + } + + printLinkedList(randInt); + + int randomIntegerToSearch = rand.nextInt(1000, 9999); + System.out.println("\nAnother random number generated is " + randomIntegerToSearch); + + int index = search(randInt, randomIntegerToSearch); + System.out.println(index); + } + + public static void printLinkedList(LinkedList ll){ + System.out.print("["); + for (Integer integer : ll) { + if (Objects.equals(integer, ll.getLast())) { + System.out.println(integer + "]"); + break; + } + System.out.print(integer + ", "); + } + } + public static LinkedList addAndSort(LinkedList ll, int value){ + //ll.add(value); + //Collections.sort(ll); This Works + + //Alternative is to loop through the list and insert the value at the correct index + for (int i = 0; i < ll.size(); i++) { + if (value < ll.get(i)) { + ll.add(i, value); + break; + } + } + + return ll; + } + + public static void swap(LinkedList ll, int indexOne, int indexTwo){ + int temp = ll.get(indexOne); + ll.set(indexOne, ll.get(indexTwo)); + ll.set(indexTwo, temp); + } + + public static int search(LinkedList list, int searchVal){ + for (Integer integer : list) { + if (integer == searchVal) { + System.out.println("Found " + searchVal + " at index " + list.indexOf(integer)); + return list.indexOf(integer); + } + } + return -1; + } +} + +\end{lstlisting} + +\begin{lstlisting}[label={list:LinkList},caption=LinkList.java Output] +Before adding: [1, 3, 5, 7, 9, 11] +After adding and sorting: [1, 3, 5, 7, 9, 10, 11] +After swapping:[1, 11, 5, 7, 9, 10, 3] +The 500 random numbers generated are: +[5140, 2654, 9650, 6208, 3285, 5870, 8415, 4470, 3292, 5109, 9747, 2996, 2697, 2965, 2092, 2340, 9688, 1416, 6545, 6487, 4031, 4935, 2186, 1660, 1387, 1604, 3315, 9312, 8201, 3766, 6869, 2948, 9840, 4919, 7098, 2844, 1423, 8388, 6944, 8689, 2253, 2349, 3053, 8613, 4073, 2687, 4510, 5683, 7515, 6510, 4708, 8513, 9960, 5186, 1779, 4222, 7884, 3039, 4489, 1495, 8465, 2574, 3107, 4125, 1184, 5148, 2088, 2074, 3744, 8362, 3632, 8889, 2990, 3160, 5612, 2702, 5432, 3411, 4386, 8549, 5264, 4654, 3231, 2641, 6005, 5929, 2808, 4568, 7724, 8545, 6653, 2882, 8376, 7078, 2184, 9273, 2099, 6183, 4012, 9545, 6913, 4132, 3493, 5904, 6853, 9254, 7793, 3168, 5212, 6519, 4972, 9487, 5869, 5483, 2048, 6566, 3173, 1376, 3291, 5639, 6290, 6948, 2285, 4691, 8525, 6715, 4300, 7707, 1212, 7013, 2793, 2816, 5154, 6177, 2513, 5160, 1169, 3522, 9254, 8663, 5847, 2297, 6056, 3298, 4464, 1348, 3088, 4748, 2952, 9422, 2408, 1016, 2278, 2899, 9530, 2531, 2884, 5474, 8693, 1192, 6024, 3681, 8855, 6679, 1082, 1591, 5889, 1675, 3996, 6724, 1923, 9263, 2845, 6660, 8871, 4396, 1866, 2981, 3851, 4887, 6493, 1801, 3104, 1817, 1974, 6150, 5140, 3885, 9704, 7804, 6548, 8148, 8148, 1882, 6748, 5225, 4651, 8040, 7697, 6017, 2045, 2335, 1186, 5728, 8235, 2649, 2974, 2281, 5102, 1182, 1483, 8741, 6740, 8155, 3097, 8990, 8104, 2531, 2465, 3053, 3527, 1877, 7297, 8537, 7119, 7861, 7527, 6972, 3059, 2964, 9109, 8366, 5064, 8960, 9113, 4413, 3397, 9594, 2844, 2537, 8949, 8363, 1335, 7825, 5092, 1487, 4303, 3024, 7311, 3089, 8365, 3269, 9683, 3195, 1920, 8125, 4941, 3182, 1478, 3290, 8295, 5685, 7451, 5847, 5367, 3331, 7911, 2760, 8549, 7343, 9024, 6815, 6924, 2094, 2998, 3157, 4569, 2093, 4675, 6744, 2895, 8084, 8614, 8453, 9492, 8584, 9370, 6607, 2248, 9621, 3197, 7886, 5800, 7759, 9254, 2246, 6267, 7150, 5415, 6560, 9630, 7852, 8695, 2926, 7301, 2082, 4559, 7903, 3526, 2740, 1180, 6096, 5915, 3697, 1062, 2550, 9672, 8396, 7711, 1517, 9738, 5090, 6433, 2905, 4780, 4820, 3003, 3276, 1072, 2252, 1503, 5251, 6978, 4992, 4922, 1889, 4002, 3729, 5753, 4632, 3582, 6036, 2606, 8320, 3832, 1757, 8862, 9066, 1717, 7205, 4933, 1431, 9813, 2974, 4707, 3334, 8474, 4348, 4306, 1800, 8563, 3164, 1419, 9400, 8810, 7017, 3922, 2391, 7801, 2272, 6614, 9316, 6509, 1759, 2940, 6521, 2784, 2886, 8195, 7072, 4500, 2884, 6492, 1676, 7204, 6054, 9121, 4462, 6390, 5965, 4183, 8756, 7622, 8132, 8743, 3366, 1251, 1229, 6151, 3927, 5405, 7189, 6319, 1256, 4355, 9667, 2299, 4497, 8437, 5226, 5316, 5378, 9691, 1596, 9387, 7033, 5787, 1722, 6389, 1815, 3883, 2641, 3488, 8028, 8874, 4700, 7825, 1715, 4137, 5165, 6384, 6476, 7985, 2361, 1378, 9432, 7383, 4831, 1267, 5819, 2865, 9034, 4533, 2343, 9981, 7449, 9535, 7119, 4554, 7902, 3630, 9828, 5574, 3708, 7472, 5022, 6656, 3721, 9429, 3682, 3080, 7998, 1930, 1860, 3590, 1056, 8884, 8227, 6516, 3601, 8520, 1454, 2728, 6416, 5097, 9983, 7685, 2223, 9105, 2145, 1604, 7275, 7339, 6000, 7857, 9790, 8742, 6900, 4998, 2831, 1877, 1675, 2051, 6158, 8537, 3502, 8439, 4232, 2970, 9007] + +Another random number generated is 9175 +-1 +\end{lstlisting} + +\pagebreak + +\section*{Question 2} + +\begin{lstlisting}[label={list:HashMap},caption=HashMap.java] +import java.util.*; + +public class lab6_Hash { + + public static void main(String[] args){ + HashMap ht = new HashMap<>(); + + ht.put(0,1); + ht.put(1,3); + ht.put(2,5); + ht.put(3,7); + ht.put(4,9); + ht.put(5,11); + + + + // Question 1 + System.out.print("Before adding: "); + printHashMap(ht); + System.out.print("After adding and sorting: "); + printHashMap(addAndSort(ht, 10)); + + // Question 2 + System.out.println("After swapping"); + swap(ht, 1, 6); + printHashMap(ht); + + //Question 3 + HashMap ranIntHash = new HashMap<>(); + Random rand = new Random(); + for (int i = 0; i < 500; i++) { + ranIntHash.put(i, rand.nextInt(1000, 9999)); + } + System.out.println("The 500 random numbers generated are: "); + printHashMap(ranIntHash); + + int randomIntegerToSearch = rand.nextInt(1000, 9999); + System.out.println("\nAnother random number generated is " + randomIntegerToSearch); + + int index = search(ranIntHash, randomIntegerToSearch); + System.out.println(index); + } + + public static void printHashMap(HashMap ht){ + System.out.print("["); + for (int i = 0; i < ht.size(); i++) { + if (Objects.equals(ht.get(i), ht.get(ht.size() - 1))) { + System.out.println(ht.get(i) + "]"); + break; + } + System.out.print(ht.get(i) + ", "); + } + } + + public static HashMap addAndSort(HashMap ht, int value){ + //Collections.sort(ht); Does Not Work + // For each value in ht, if value is less than value, insert value at that index + for (int i = 0; i < ht.size(); i++) { + if (value < ht.get(i)) { + ht.put(ht.size(), ht.get(ht.size() - 1)); + // Shift all values to the right of i to the right + for (int j = ht.size() - 2; j > i; j--) { + ht.put(j, ht.get(j - 1)); + } + ht.put(i, value); + break; + } + + } + + return ht; + } + + public static void swap(HashMap ht, int indexOne, int indexTwo){ + // Swap the values at indexOne and indexTwo + int temp = ht.get(indexOne); + ht.put(indexOne, ht.get(indexTwo)); + ht.put(indexTwo, temp); + } + + public static int search(HashMap ht, int searchVal){ + // Return index of searchVal if found, else return -1 + for (int i = 0; i < ht.size(); i++) { + if (ht.get(i) == searchVal) { + return i; + } + } + return -1; + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:HashtableOutput},caption=HashMap.java Output] +Before adding: [1, 3, 5, 7, 9, 11] +After adding and sorting: [1, 3, 5, 7, 9, 10, 11] +After swapping +[1, 11, 5, 7, 9, 10, 3] +The 500 random numbers generated are: +[7606, 4198, 4276, 8580, 7185, 1550, 6018, 9282, 1320, 8666, 3682, 8337, 9745, 5519, 7117, 5320, 2911, 7779, 8901, 3576, 3489, 3918, 5158, 5767, 1395, 4137, 9054, 3402, 5522, 4599, 6531, 1672, 7938, 5141, 5111, 8044, 2589, 8616, 7610, 1656, 7196, 9167, 8137, 7973, 6642, 9944, 2251, 3728, 6113, 6484, 2363, 1541, 8455, 5699, 6115, 9768, 5560, 8505, 3596, 2276, 4169, 2980, 5803, 2475, 6017, 3230, 4428, 3002, 3439, 2969, 7542, 8097, 5038, 1168, 6683, 4387, 4053, 4353, 2561, 7144, 6977, 2815, 7440, 4012, 8442, 7500, 8250, 9178, 6535, 5550, 8498, 1509, 7671, 1196, 7372, 2979, 8323, 6679, 7594, 2858, 1493, 7237, 1190, 9001, 9653, 1197, 2399, 7212, 5594, 9258, 9912, 7660, 3775, 6058, 4870, 8644, 8009, 3493, 2154, 5853, 9111, 5719, 2819, 2427, 6430, 3178, 4578, 8065, 3181, 9754, 2461, 1664, 1065, 6709, 5965, 7019, 5408, 4910, 3581, 9569, 3041, 6541, 3727, 2855, 5925, 4933, 5857, 9384, 1579, 8652, 4429, 8008, 7679, 7766, 5219, 3135, 9809, 8174, 1512, 7082, 9372, 2275, 1510, 6569, 9900, 1956, 8527, 1889, 1062, 4517, 8568, 5561, 5088, 8729, 9082, 4388, 8821, 3514, 1350, 2022, 6163, 6149, 8740, 5193, 4359, 6804, 7682, 1883, 5114, 8859, 5888, 8917, 8888, 8838, 7074, 5897, 1425, 1417, 5360, 3652, 8624, 3339, 1497, 6503, 8791, 3499, 5362, 1415, 1954, 9325, 7909, 5220, 8422, 5227, 2398, 9059, 9868, 6811, 1148, 3049, 3202, 1367, 5193, 9612, 1716, 3476, 3751, 9261, 1791, 3598, 9949, 7567, 3234, 5227, 6091, 9223, 6663, 9527, 3747, 6962, 2642, 7850, 4530, 5711, 7435, 6896, 9081, 8683, 3124, 6691, 2625, 9444, 5781, 8965, 1953, 3084, 5215, 5745, 5448, 6710, 6482, 7937, 5487, 9130, 6340, 4144, 4257, 4228, 6299, 5861, 5984, 1286, 9481, 4909, 8908, 1689, 2240, 8113, 5134, 8428, 1296, 9206, 2382, 7786, 8356, 5399, 8712, 3676, 1942, 5100, 5346, 2929, 4966, 4612, 8587, 6916, 7630, 5597, 6134, 4507, 8512, 4782, 8147, 8763, 3698, 7896, 8663, 7661, 9060, 9757, 9811, 4351, 4171, 9060, 6882, 9099, 5857, 1857, 3567, 5534, 1795, 7141, 4051, 1324, 5898, 5387, 4393, 8682, 5117, 6216, 5507, 7927, 3160, 9319, 8227, 7456, 9495, 1169, 8867, 1494, 1053, 8256, 9698, 5844, 7399, 6841, 1805, 7273, 6921, 7885, 1397, 2238, 1589, 8858, 8821, 2298, 5419, 4156, 9401, 9434, 6104, 1335, 9990, 2109, 4885, 4129, 1290, 3527, 9021, 8575, 4381, 1771, 2425, 9850, 8656, 7421, 9177, 2525, 4816, 5808, 2838, 8942, 3375, 8391, 5823, 6589, 1270, 4564, 3962, 1661, 6562, 5324, 4463, 7308, 4539, 8346, 3699, 2016, 4619, 9447, 9338, 7002, 3790, 1197, 3944, 4517, 3192, 8291, 7833, 9725, 4981, 8191, 5600, 6463, 6453, 4346, 1438, 4136, 9413, 1358, 5582, 7457, 8920, 9506, 8360, 5092, 1332, 3405, 1783, 1681, 9989, 4926, 8995, 6766, 5558, 2913, 4523, 5819, 7962, 5223, 9549, 5783, 5665, 5713, 2897, 2142, 7284, 5442, 7908, 6458, 7641, 3259, 5826, 6234, 4535, 3556, 1435, 5715, 3683, 4237, 2381, 6668, 7494, 1340, 5201, 8728, 8671, 4965, 1067, 7546, 1978, 5781, 8997, 8441, 1199, 3915, 4484, 8278, 7813, 9373, 1209, 7920, 5873, 5338, 7532, 8476, 9402, 6108, 1139, 1439, 4465, 2731, 8226, 1429, 7648, 1022, 6853, 6570, 7177, 4989] + +Another random number generated is 1101 +-1 +\end{lstlisting} +\end{document} diff --git a/Week6_Lab/lab6_Hash.java b/Week6_Lab/lab6_Hash.java new file mode 100644 index 0000000..0822221 --- /dev/null +++ b/Week6_Lab/lab6_Hash.java @@ -0,0 +1,93 @@ +package Week6_Lab; + +import java.util.*; + +public class lab6_Hash { + + public static void main(String[] args){ + HashMap ht = new HashMap<>(); + + ht.put(0,1); + ht.put(1,3); + ht.put(2,5); + ht.put(3,7); + ht.put(4,9); + ht.put(5,11); + + + + // Question 1 + System.out.print("Before adding: "); + printHashMap(ht); + System.out.print("After adding and sorting: "); + printHashMap(addAndSort(ht, 10)); + + // Question 2 + System.out.println("After swapping"); + swap(ht, 1, 6); + printHashMap(ht); + + //Question 3 + HashMap ranIntHash = new HashMap<>(); + Random rand = new Random(); + for (int i = 0; i < 500; i++) { + ranIntHash.put(i, rand.nextInt(1000, 9999)); + } + System.out.println("The 500 random numbers generated are: "); + printHashMap(ranIntHash); + + int randomIntegerToSearch = rand.nextInt(1000, 9999); + System.out.println("\nAnother random number generated is " + randomIntegerToSearch); + + int index = search(ranIntHash, randomIntegerToSearch); + System.out.println(index); + } + + public static void printHashMap(HashMap ht){ + System.out.print("["); + for (int i = 0; i < ht.size(); i++) { + if (Objects.equals(ht.get(i), ht.get(ht.size() - 1))) { + System.out.println(ht.get(i) + "]"); + break; + } + System.out.print(ht.get(i) + ", "); + } + } + + public static HashMap addAndSort(HashMap ht, int value){ + //Collections.sort(ht); Does Not Work + // For each value in ht, if value is less than value, insert value at that index + for (int i = 0; i < ht.size(); i++) { + if (value < ht.get(i)) { + ht.put(ht.size(), ht.get(ht.size() - 1)); + // Shift all values to the right of i to the right + for (int j = ht.size() - 2; j > i; j--) { + ht.put(j, ht.get(j - 1)); + } + ht.put(i, value); + break; + } + + } + + return ht; + } + + public static void swap(HashMap ht, int indexOne, int indexTwo){ + // Swap the values at indexOne and indexTwo + int temp = ht.get(indexOne); + ht.put(indexOne, ht.get(indexTwo)); + ht.put(indexTwo, temp); + } + + public static int search(HashMap ht, int searchVal){ + // Return index of searchVal if found, else return -1 + for (int i = 0; i < ht.size(); i++) { + if (ht.get(i) == searchVal) { + return i; + } + } + return -1; + } +} + diff --git a/Week6_Lab/lab6_LL.java b/Week6_Lab/lab6_LL.java new file mode 100644 index 0000000..658c1dd --- /dev/null +++ b/Week6_Lab/lab6_LL.java @@ -0,0 +1,85 @@ +package Week6_Lab; +import java.util.*; +public class lab6_LL { + + public static void main(String[] args){ + LinkedList ll = new LinkedList(); + + ll.add(1); + ll.add(3); + ll.add(5); + ll.add(7); + ll.add(9); + ll.add(11); + + // Question 1 + System.out.print("Before adding: "); + printLinkedList(ll); + System.out.print("After adding and sorting: "); + printLinkedList(addAndSort(ll, 10)); + + // Question 2 + //System.out.print("Before swapping:"); + //printLinkedList(ll); + System.out.print("After swapping:"); + swap(ll, 1, 6); + printLinkedList(ll); + + //Question 3 + LinkedList randInt = new LinkedList(); + Random rand = new Random(); + System.out.println("The 500 random numbers generated are: "); + for (int i = 0; i < 500; i++) { + randInt.add(rand.nextInt(1000, 9999)); + } + + printLinkedList(randInt); + + int randomIntegerToSearch = rand.nextInt(1000, 9999); + System.out.println("\nAnother random number generated is " + randomIntegerToSearch); + + int index = search(randInt, randomIntegerToSearch); + System.out.println(index); + } + + public static void printLinkedList(LinkedList ll){ + System.out.print("["); + for (Integer integer : ll) { + if (Objects.equals(integer, ll.getLast())) { + System.out.println(integer + "]"); + break; + } + System.out.print(integer + ", "); + } + } + public static LinkedList addAndSort(LinkedList ll, int value){ + //ll.add(value); + //Collections.sort(ll); This Works + + //Alternative is to loop through the list and insert the value at the correct index + for (int i = 0; i < ll.size(); i++) { + if (value < ll.get(i)) { + ll.add(i, value); + break; + } + } + + return ll; + } + + public static void swap(LinkedList ll, int indexOne, int indexTwo){ + int temp = ll.get(indexOne); + ll.set(indexOne, ll.get(indexTwo)); + ll.set(indexTwo, temp); + } + + public static int search(LinkedList list, int searchVal){ + for (Integer integer : list) { + if (integer == searchVal) { + System.out.println("Found " + searchVal + " at index " + list.indexOf(integer)); + return list.indexOf(integer); + } + } + return -1; + } +} diff --git a/Week8_Lab/BankDemoTest.java b/Week8_Lab/BankDemoTest.java new file mode 100644 index 0000000..31b29bf --- /dev/null +++ b/Week8_Lab/BankDemoTest.java @@ -0,0 +1,23 @@ +package Week8_Lab; +import java.util.Scanner; +public class BankDemoTest { + public static void main(String[] args){ + CheckingAccount c = new CheckingAccount(); + Scanner sc = new Scanner(System.in); + + System.out.print("Enter an amount to deposit: "); + double amount = sc.nextDouble(); + c.deposit(amount); + System.out.print("Enter an amount to withdraw: "); + amount = sc.nextDouble(); + try{ + c.withdraw(amount); + }catch(InsufficientFundsException e){ + if (e.getAmount() > c.getBalance()){ + System.out.println("Sorry, but your account is short by: $" + (e.getAmount() - c.getBalance())); + } + } + if (amount <= c.getBalance()) + System.out.println("The balance after withdrawal is: $" + (c.getBalance() - amount)); + } +} diff --git a/Week8_Lab/CheckingAccount.java b/Week8_Lab/CheckingAccount.java new file mode 100644 index 0000000..646791e --- /dev/null +++ b/Week8_Lab/CheckingAccount.java @@ -0,0 +1,36 @@ +package Week8_Lab; + +public class CheckingAccount extends InsufficientFundsException{ + + private double balance; + private int number; + + public CheckingAccount(double amount) { + super(amount); + } + + public CheckingAccount(){ + this(0); + } + + public void deposit(double amount){ + if (amount > 0){ + this.balance += amount; + } + } + + public void withdraw(double amount) throws InsufficientFundsException{ + if (amount > this.balance){ + throw new InsufficientFundsException(amount); + } + } + public double getBalance(){ + return this.balance; + } + + public int getNumber(){ + return this.number; + } + + +} diff --git a/Week8_Lab/CircleWithException.java b/Week8_Lab/CircleWithException.java new file mode 100644 index 0000000..0afec12 --- /dev/null +++ b/Week8_Lab/CircleWithException.java @@ -0,0 +1,57 @@ +package Week8_Lab; + +import java.util.Scanner; + +public class CircleWithException { + private double radius; + + public CircleWithException(double radius) throws IllegalArgumentException { + if (radius < 0) { + throw new IllegalArgumentException("Radius cannot be negative"); + } + this.radius = radius; + } + + public double getRadius() { + return radius; + } + + public void setRadius(double radius) throws IllegalArgumentException { + if (radius < 0) { + throw new IllegalArgumentException("Radius cannot be negative"); + } + this.radius = radius; + } + + public double getArea() throws Exception{ + double area = Math.PI * radius * radius; + + if (area > 1000){ + throw new Exception("Area cannot be greater than 1000"); + } + return area; + } + + // Exceptions not stated in Lab Instructions + public double getDiameter() { + return radius * 2; + } + + public static void main(String[] args) { + CircleWithException c1 = new CircleWithException(5); + Scanner sc = new Scanner(System.in); + System.out.print("Enter a radius: "); + double radius = sc.nextDouble(); + try { + CircleWithException c2 = new CircleWithException(radius); + System.out.println("Radius: " + c2.getRadius()); + System.out.println("Area: " + c2.getArea()); + System.out.println("Diameter: " + c2.getDiameter()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + +} diff --git a/Week8_Lab/InsufficientFundsException.java b/Week8_Lab/InsufficientFundsException.java new file mode 100644 index 0000000..25dfb6f --- /dev/null +++ b/Week8_Lab/InsufficientFundsException.java @@ -0,0 +1,11 @@ +package Week8_Lab; + +public class InsufficientFundsException extends Throwable{ + private double amount; + public InsufficientFundsException(double amount){ + this.amount = amount; + } + public double getAmount(){ + return amount; + } +} diff --git a/Week8_Lab/Submission/CSC1109_Lab7_2200624.pdf b/Week8_Lab/Submission/CSC1109_Lab7_2200624.pdf new file mode 100644 index 0000000..a4474fa Binary files /dev/null and b/Week8_Lab/Submission/CSC1109_Lab7_2200624.pdf differ diff --git a/Week8_Lab/Submission/CSC1109_Lab7_2200624.tex b/Week8_Lab/Submission/CSC1109_Lab7_2200624.tex new file mode 100644 index 0000000..e89c1c9 --- /dev/null +++ b/Week8_Lab/Submission/CSC1109_Lab7_2200624.tex @@ -0,0 +1,268 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 7} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 7} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +\begin{lstlisting}[label={list:CircleWithException},caption=CircleWithException.java] +import java.util.Scanner; + +public class CircleWithException { + private double radius; + + public CircleWithException(double radius) throws IllegalArgumentException { + if (radius < 0) { + throw new IllegalArgumentException("Radius cannot be negative"); + } + this.radius = radius; + } + + public double getRadius() { + return radius; + } + + public void setRadius(double radius) throws IllegalArgumentException { + if (radius < 0) { + throw new IllegalArgumentException("Radius cannot be negative"); + } + this.radius = radius; + } + + public double getArea() throws Exception{ + double area = Math.PI * radius * radius; + + if (area > 1000){ + throw new Exception("Area cannot be greater than 1000"); + } + return area; + } + + // Exceptions not stated in Lab Instructions + public double getDiameter() { + return radius * 2; + } + + public static void main(String[] args) { + CircleWithException c1 = new CircleWithException(5); + Scanner sc = new Scanner(System.in); + System.out.print("Enter a radius: "); + double radius = sc.nextDouble(); + try { + CircleWithException c2 = new CircleWithException(radius); + System.out.println("Radius: " + c2.getRadius()); + System.out.println("Area: " + c2.getArea()); + System.out.println("Diameter: " + c2.getDiameter()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + +} +\end{lstlisting} + +\begin{lstlisting}[label={list:CircleWithException},caption=CircleWithException.java Output] +// Negative radius +Enter a radius: -10 +Radius cannot be negative + +// Area Greater than 1000 +Enter a radius: 1000 +Radius: 1000.0 +Area cannot be greater than 1000 + +// Valid Circle +Enter a radius: 5 +Radius: 5.0 +Area: 78.53981633974483 +Diameter: 10.0 +\end{lstlisting} + +\pagebreak + +\section*{Question 2} + +\begin{lstlisting}[label={list:InsufficientFundsException},caption=InsufficientFundsException.java] +public class InsufficientFundsException extends Exception{ + private double amount; + public InsufficientFundsException(double amount){ + this.amount = amount; + } + public double getAmount(){ + return amount; + } +} + +\end{lstlisting} + +\begin{lstlisting}[label={list:CheckingAccount},caption=CheckingAccount.java] +public class CheckingAccount extends InsufficientFundsException{ + + private double balance; + private int number; + + public CheckingAccount(double amount) { + super(amount); + } + + public CheckingAccount(){ + this(0); + } + + public void deposit(double amount){ + if (amount > 0){ + this.balance += amount; + } + } + + public void withdraw(double amount) throws InsufficientFundsException{ + if (amount > this.balance){ + throw new InsufficientFundsException(amount); + } + } + public double getBalance(){ + return this.balance; + } + + public int getNumber(){ + return this.number; + } + + +} +\end{lstlisting} + +\begin{lstlisting}[label={list:BankDemoTest},caption=BankDemoTest.java] +import java.util.Scanner; +public class BankDemoTest { + public static void main(String[] args){ + CheckingAccount c = new CheckingAccount(); + Scanner sc = new Scanner(System.in); + + System.out.print("Enter an amount to deposit: "); + double amount = sc.nextDouble(); + c.deposit(amount); + System.out.print("Enter an amount to withdraw: "); + amount = sc.nextDouble(); + try{ + c.withdraw(amount); + }catch(InsufficientFundsException e){ + if (e.getAmount() > c.getBalance()){ + System.out.println("Sorry, but your account is short by: $" + (e.getAmount() - c.getBalance())); + } + } + if (amount <= c.getBalance()) + System.out.println("The balance after withdrawal is: $" + (c.getBalance() - amount)); + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:BankDemoTestOutput},caption=BankDemoTest.java Output] +// $yy < $xx +Enter an amount to deposit: 100 +Enter an amount to withdraw: 20 +The balance after withdrawal is: $80.0 + +// $yy > $xx +Enter an amount to deposit: 100 +Enter an amount to withdraw: 254 +Sorry, but your account is short by: $154.0 +\end{lstlisting} +\end{document} diff --git a/Week8_Lab/Submission/CSC1109_Lab8_2200624.pdf b/Week8_Lab/Submission/CSC1109_Lab8_2200624.pdf new file mode 100644 index 0000000..e6ebf04 Binary files /dev/null and b/Week8_Lab/Submission/CSC1109_Lab8_2200624.pdf differ diff --git a/Week8_Lab/Submission/CSC1109_Lab8_2200624.tex b/Week8_Lab/Submission/CSC1109_Lab8_2200624.tex new file mode 100644 index 0000000..c967e0a --- /dev/null +++ b/Week8_Lab/Submission/CSC1109_Lab8_2200624.tex @@ -0,0 +1,268 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 8} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 8} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +\begin{lstlisting}[label={list:CircleWithException},caption=CircleWithException.java] +import java.util.Scanner; + +public class CircleWithException { + private double radius; + + public CircleWithException(double radius) throws IllegalArgumentException { + if (radius < 0) { + throw new IllegalArgumentException("Radius cannot be negative"); + } + this.radius = radius; + } + + public double getRadius() { + return radius; + } + + public void setRadius(double radius) throws IllegalArgumentException { + if (radius < 0) { + throw new IllegalArgumentException("Radius cannot be negative"); + } + this.radius = radius; + } + + public double getArea() throws Exception{ + double area = Math.PI * radius * radius; + + if (area > 1000){ + throw new Exception("Area cannot be greater than 1000"); + } + return area; + } + + // Exceptions not stated in Lab Instructions + public double getDiameter() { + return radius * 2; + } + + public static void main(String[] args) { + CircleWithException c1 = new CircleWithException(5); + Scanner sc = new Scanner(System.in); + System.out.print("Enter a radius: "); + double radius = sc.nextDouble(); + try { + CircleWithException c2 = new CircleWithException(radius); + System.out.println("Radius: " + c2.getRadius()); + System.out.println("Area: " + c2.getArea()); + System.out.println("Diameter: " + c2.getDiameter()); + } catch (IllegalArgumentException e) { + System.out.println(e.getMessage()); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + +} +\end{lstlisting} + +\begin{lstlisting}[label={list:CircleWithException},caption=CircleWithException.java Output] +// Negative radius +Enter a radius: -10 +Radius cannot be negative + +// Area Greater than 1000 +Enter a radius: 1000 +Radius: 1000.0 +Area cannot be greater than 1000 + +// Valid Circle +Enter a radius: 5 +Radius: 5.0 +Area: 78.53981633974483 +Diameter: 10.0 +\end{lstlisting} + +\pagebreak + +\section*{Question 2} + +\begin{lstlisting}[label={list:InsufficientFundsException},caption=InsufficientFundsException.java] +public class InsufficientFundsException extends Exception{ + private double amount; + public InsufficientFundsException(double amount){ + this.amount = amount; + } + public double getAmount(){ + return amount; + } +} + +\end{lstlisting} + +\begin{lstlisting}[label={list:CheckingAccount},caption=CheckingAccount.java] +public class CheckingAccount extends InsufficientFundsException{ + + private double balance; + private int number; + + public CheckingAccount(double amount) { + super(amount); + } + + public CheckingAccount(){ + this(0); + } + + public void deposit(double amount){ + if (amount > 0){ + this.balance += amount; + } + } + + public void withdraw(double amount) throws InsufficientFundsException{ + if (amount > this.balance){ + throw new InsufficientFundsException(amount); + } + } + public double getBalance(){ + return this.balance; + } + + public int getNumber(){ + return this.number; + } + + +} +\end{lstlisting} + +\begin{lstlisting}[label={list:BankDemoTest},caption=BankDemoTest.java] +import java.util.Scanner; +public class BankDemoTest { + public static void main(String[] args){ + CheckingAccount c = new CheckingAccount(); + Scanner sc = new Scanner(System.in); + + System.out.print("Enter an amount to deposit: "); + double amount = sc.nextDouble(); + c.deposit(amount); + System.out.print("Enter an amount to withdraw: "); + amount = sc.nextDouble(); + try{ + c.withdraw(amount); + }catch(InsufficientFundsException e){ + if (e.getAmount() > c.getBalance()){ + System.out.println("Sorry, but your account is short by: $" + (e.getAmount() - c.getBalance())); + } + } + if (amount <= c.getBalance()) + System.out.println("The balance after withdrawal is: $" + (c.getBalance() - amount)); + } +} +\end{lstlisting} + +\begin{lstlisting}[label={list:BankDemoTestOutput},caption=BankDemoTest.java Output] +// $yy < $xx +Enter an amount to deposit: 100 +Enter an amount to withdraw: 20 +The balance after withdrawal is: $80.0 + +// $yy > $xx +Enter an amount to deposit: 100 +Enter an amount to withdraw: 254 +Sorry, but your account is short by: $154.0 +\end{lstlisting} +\end{document} diff --git a/Week9_Lab/RandomCharacter.java b/Week9_Lab/RandomCharacter.java new file mode 100644 index 0000000..d828236 --- /dev/null +++ b/Week9_Lab/RandomCharacter.java @@ -0,0 +1,69 @@ +package Week9_Lab; + +public class RandomCharacter { + + public static char getRandomLowerCaseLetter(){ + return (char)('a' + Math.random() * ('z' - 'a' + 1)); + } + public static char getRandomUpperCaseLetter(){ + return (char)('A' + Math.random() * ('Z' - 'A' + 1)); + } + public static char getRandomDigitCharacter(){ + return (char)('0' + Math.random() * ('9' - '0' + 1)); + } + public static char getRandomCharacter(){ + int num = (int)(Math.random() * 3); + return switch (num) { + case 0 -> getRandomLowerCaseLetter(); + case 1 -> getRandomUpperCaseLetter(); + case 2 -> getRandomDigitCharacter(); + default -> ' '; + }; + } + + public int genPrime() { + int num; + do { + num = 0; + for (int i = 0; i < 10; i++) { + num = num * 10 + (getRandomDigitCharacter() - '0'); + } + } while (!isPrime(num) || (int) (Math.log10(num) + 1) != 10); + return num; + } + + public boolean isPrime(int inputNum){ + if (inputNum <= 3 || inputNum % 2 == 0) + return inputNum == 2 || inputNum == 3; + + int divisor = 3; + while ((divisor <= Math.sqrt(inputNum)) && (inputNum % divisor != 0)) + divisor += 2; + return inputNum % divisor != 0; + } + + public static void main(String[] args) { + for (int i = 0; i < 15; i++){ + System.out.print(getRandomLowerCaseLetter() + " "); + } + System.out.println(); + + for (int i = 0; i < 15; i++){ + System.out.print(getRandomUpperCaseLetter() + " "); + } + System.out.println(); + + for (int i = 0; i < 15; i++){ + System.out.print(getRandomDigitCharacter() + " "); + } + System.out.println(); + + for (int i = 0; i < 15; i++){ + System.out.print(getRandomCharacter() + " "); + } + System.out.println(); + + System.out.println(new RandomCharacter().genPrime()); + + } +} diff --git a/Week9_Lab/RandomCharacterTest.java b/Week9_Lab/RandomCharacterTest.java new file mode 100644 index 0000000..ee77989 --- /dev/null +++ b/Week9_Lab/RandomCharacterTest.java @@ -0,0 +1,40 @@ +package Week9_Lab; +import org.junit.Test; +import static org.junit.Assert.*; + +public class RandomCharacterTest { + @Test + public void testGetRandomLowerCaseLetter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomLowerCaseLetter(); + assertTrue(c >= 'a' && c <= 'z'); + } + } + + @Test + public void testGetRandomUpperCaseLetter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomUpperCaseLetter(); + assertTrue(c >= 'A' && c <= 'Z'); + } + } + + @Test + public void testGetRandomDigitCharacter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomDigitCharacter(); + assertTrue(c >= '0' && c <= '9'); + } + } + + @Test + public void testGetRandomCharacter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomCharacter(); + assertTrue((c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') + ); + } + } +} diff --git a/Week9_Lab/Submission/CSC1109_Lab9_2200624.pdf b/Week9_Lab/Submission/CSC1109_Lab9_2200624.pdf new file mode 100644 index 0000000..120a426 Binary files /dev/null and b/Week9_Lab/Submission/CSC1109_Lab9_2200624.pdf differ diff --git a/Week9_Lab/Submission/CSC1109_Lab9_2200624.tex b/Week9_Lab/Submission/CSC1109_Lab9_2200624.tex new file mode 100644 index 0000000..3842c16 --- /dev/null +++ b/Week9_Lab/Submission/CSC1109_Lab9_2200624.tex @@ -0,0 +1,245 @@ +\documentclass[a4paper,11pt]{article} + +\usepackage[T1]{fontenc} +\usepackage[utf8]{inputenc} +\usepackage{graphicx} +\usepackage{xcolor} + +\renewcommand\familydefault{\sfdefault} +\usepackage{tgheros} +\usepackage[defaultmono]{droidsansmono} + +\usepackage{amsmath,amssymb,amsthm,textcomp} +\usepackage{enumerate} +\usepackage{multicol} +\usepackage{tikz} + +\usepackage{geometry} +\geometry{left=25mm,right=25mm,% +bindingoffset=0mm, top=20mm,bottom=20mm} + +% Image path +\graphicspath{{images/}} + +\linespread{1.3} + +\newcommand{\linia}{\rule{\linewidth}{0.5pt}} + +% custom theorems if needed +\newtheoremstyle{mytheor} + {1ex}{1ex}{\normalfont}{0pt}{\scshape}{.}{1ex} + {{\thmname{#1 }}{\thmnumber{#2}}{\thmnote{ (#3)}}} + +\theoremstyle{mytheor} +\newtheorem{defi}{Definition} + +% my own titles +\makeatletter +\renewcommand{\maketitle}{ +\begin{center} +\vspace{2ex} +{\huge \textsc{\@title}} +\vspace{1ex} +\\ +\linia\\ +\@author \hfill \@date +\vspace{4ex} +\end{center} +} +\makeatother +%%% + +% custom footers and headers +\usepackage{fancyhdr} +\pagestyle{fancy} +\lhead{} +\chead{} +\rhead{} +\lfoot{CSC 1109 Lab 9} +\cfoot{} +\rfoot{Page \thepage} +\renewcommand{\headrulewidth}{0pt} +\renewcommand{\footrulewidth}{0pt} +% + +% code listing settings +\usepackage{listings} +\lstset{ + language=java, + basicstyle=\ttfamily\small, + aboveskip={1.0\baselineskip}, + belowskip={1.0\baselineskip}, + columns=fixed, + extendedchars=true, + breaklines=true, + tabsize=4, + prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}, + frame=lines, + showtabs=false, + showspaces=false, + showstringspaces=false, + keywordstyle=\color[rgb]{0.627,0.126,0.941}, + commentstyle=\color[rgb]{0.133,0.545,0.133}, + stringstyle=\color[rgb]{01,0,0}, + numbers=left, + numberstyle=\small, + stepnumber=1, + numbersep=10pt, + captionpos=t, + escapeinside={\%*}{*)} +} + +%%%----------%%%----------%%%----------%%%----------%%% + +\begin{document} + +\title{CSC 1109 Lab 9} + +\author{Woon Jun Wei, 2200624} + +\date{\today} + +\maketitle + +\section*{Question 1} +\begin{lstlisting}[label={list:RandomCharacter},caption=RandomCharacter.java] + +public class RandomCharacter { + + public static char getRandomLowerCaseLetter(){ + return (char)('a' + Math.random() * ('z' - 'a' + 1)); + } + public static char getRandomUpperCaseLetter(){ + return (char)('A' + Math.random() * ('Z' - 'A' + 1)); + } + public static char getRandomDigitCharacter(){ + return (char)('0' + Math.random() * ('9' - '0' + 1)); + } + public static char getRandomCharacter(){ + int num = (int)(Math.random() * 3); + return switch (num) { + case 0 -> getRandomLowerCaseLetter(); + case 1 -> getRandomUpperCaseLetter(); + case 2 -> getRandomDigitCharacter(); + default -> ' '; + }; + } + + public int genPrime() { + int num; + do { + num = 0; + for (int i = 0; i < 10; i++) { + num = num * 10 + (getRandomDigitCharacter() - '0'); + } + } while (!isPrime(num) || (int) (Math.log10(num) + 1) != 10); + return num; + } + + public boolean isPrime(int inputNum){ + if (inputNum <= 3 || inputNum % 2 == 0) + return inputNum == 2 || inputNum == 3; + + int divisor = 3; + while ((divisor <= Math.sqrt(inputNum)) && (inputNum % divisor != 0)) + divisor += 2; + return inputNum % divisor != 0; + } + + public static void main(String[] args) { + for (int i = 0; i < 15; i++){ + System.out.print(getRandomLowerCaseLetter() + " "); + } + System.out.println(); + + for (int i = 0; i < 15; i++){ + System.out.print(getRandomUpperCaseLetter() + " "); + } + System.out.println(); + + for (int i = 0; i < 15; i++){ + System.out.print(getRandomDigitCharacter() + " "); + } + System.out.println(); + + for (int i = 0; i < 15; i++){ + System.out.print(getRandomCharacter() + " "); + } + System.out.println(); + + System.out.println(new RandomCharacter().genPrime()); + + } +} +\end{lstlisting} +\pagebreak +\begin{lstlisting}[label={list:RandomCharacterOutput},caption=Output of RandomCharacter.java] +//Output 1 +q e s o u e b e j j o s l c t +M G G C J Q T F F W Z A A J E +8 0 7 7 8 9 3 8 9 7 2 2 3 6 7 +u R 7 G 4 b 2 0 n 7 a 8 6 6 X +1174095277 + +//Output 2 +s b w w j q z u t a q l t t o +I R C J K D Z S O E Z G D B I +9 3 0 8 9 2 1 9 8 9 2 0 6 6 2 +Y k N l b T M 9 R 4 8 8 d G H +1293553021 +\end{lstlisting} + +\pagebreak +\begin{lstlisting}[label={list:RandomCharacterTest},caption=Test cases of RandomCharacter.java, RandomCharacterTest.java] +import org.junit.Test; +import static org.junit.Assert.*; + +public class RandomCharacterTest { + @Test + public void testGetRandomLowerCaseLetter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomLowerCaseLetter(); + assertTrue(c >= 'a' && c <= 'z'); + } + } + + @Test + public void testGetRandomUpperCaseLetter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomUpperCaseLetter(); + assertTrue(c >= 'A' && c <= 'Z'); + } + } + + @Test + public void testGetRandomDigitCharacter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomDigitCharacter(); + assertTrue(c >= '0' && c <= '9'); + } + } + + @Test + public void testGetRandomCharacter() { + for (int i = 0; i < 1000;i++){ + char c = RandomCharacter.getRandomCharacter(); + assertTrue((c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') + ); + } + } +} +\end{lstlisting} +\pagebreak +{\huge\textbf{RandomCharacterTest.java Output}} +% Insert image +\begin{figure}[ht] + \centering + \includegraphics[width=0.8\textwidth]{testcase.png} + \caption{Output of RandomCharacterTest.java} + \label{fig:RandomCharacterTest} +\end{figure} + + +\end{document} diff --git a/Week9_Lab/Submission/images/testcase.png b/Week9_Lab/Submission/images/testcase.png new file mode 100644 index 0000000..c031109 Binary files /dev/null and b/Week9_Lab/Submission/images/testcase.png differ