Develop #8

Closed
Razia wants to merge 2 commits from Razia/HW-03-oop-and-api:develop into main
6 changed files with 170 additions and 129 deletions
+2 -10
View File
@@ -5,7 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.to</groupId> <groupId>org.to</groupId>
<artifactId>HW03</artifactId> <artifactId>HW</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<properties> <properties>
@@ -14,18 +14,10 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<!-- GSON: Google JSON parsing library -->
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>2.11.0</version> <version>2.10.1</version>
</dependency>
<!-- Jackson: Another JSON parsing library -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency> </dependency>
</dependencies> </dependencies>
+18 -32
View File
@@ -4,7 +4,6 @@ public class Rational {
private int numerator; private int numerator;
private int denominator; private int denominator;
// Constructor
public Rational(int numerator, int denominator) { public Rational(int numerator, int denominator) {
if (denominator == 0) { if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be zero"); throw new IllegalArgumentException("Denominator cannot be zero");
@@ -14,7 +13,6 @@ public class Rational {
simplify(); simplify();
} }
// GCD helper for simplification
private int gcd(int a, int b) { private int gcd(int a, int b) {
a = Math.abs(a); a = Math.abs(a);
b = Math.abs(b); b = Math.abs(b);
@@ -26,73 +24,62 @@ public class Rational {
return a; return a;
} }
// Simplify the fraction
private void simplify() { private void simplify() {
int gcd = gcd(numerator, denominator); int gcd = gcd(numerator, denominator);
numerator /= gcd; numerator /= gcd;
denominator /= gcd; denominator /= gcd;
// Keep denominator positive
if (denominator < 0) { if (denominator < 0) {
numerator = -numerator; numerator = -numerator;
denominator = -denominator; denominator = -denominator;
} }
} }
// COMPLETED - Instance method: this + other
public Rational add(Rational other) { public Rational add(Rational other) {
int newNumerator = this.numerator * other.denominator + other.numerator * this.denominator; int newNumerator = this.numerator * other.denominator + other.numerator * this.denominator;
int newDenominator = this.denominator * other.denominator; int newDenominator = this.denominator * other.denominator;
return new Rational(newNumerator, newDenominator); return new Rational(newNumerator, newDenominator);
} }
// COMPLETED - Static method: r1 + r2
public static Rational add(Rational r1, Rational r2) { public static Rational add(Rational r1, Rational r2) {
return r1.add(r2); return r1.add(r2);
} }
// TODO: Instance method - this - other // a/b - c/d = (a*d - c*b) / (b*d)
// Formula: a/b - c/d = (a*d - c*b) / (b*d)
public Rational subtract(Rational other) { public Rational subtract(Rational other) {
// YOUR CODE HERE int newNumerator = this.numerator * other.denominator - other.numerator * this.denominator;
return null; // Remove this line when implemented int newDenominator = this.denominator * other.denominator;
return new Rational(newNumerator, newDenominator);
} }
// TODO: Static method - r1 - r2
public static Rational subtract(Rational r1, Rational r2) { public static Rational subtract(Rational r1, Rational r2) {
// YOUR CODE HERE return r1.subtract(r2);
return null; // Remove this line when implemented
} }
// TODO: Instance method - this * other // (a/b) * (c/d) = (a*c) / (b*d)
// Formula: (a/b) * (c/d) = (a*c) / (b*d)
public Rational multiply(Rational other) { public Rational multiply(Rational other) {
// YOUR CODE HERE int newNumerator = this.numerator * other.numerator;
return null; // Remove this line when implemented int newDenominator = this.denominator * other.denominator;
return new Rational(newNumerator, newDenominator);
} }
// TODO: Static method - r1 * r2
public static Rational multiply(Rational r1, Rational r2) { public static Rational multiply(Rational r1, Rational r2) {
// YOUR CODE HERE return r1.multiply(r2);
return null; // Remove this line when implemented
} }
// TODO: Instance method - this / other // (a/b) ÷ (c/d) = (a*d) / (b*c)
// Formula: (a/b) ÷ (c/d) = (a*d) / (b*c)
public Rational divide(Rational other) { public Rational divide(Rational other) {
// YOUR CODE HERE if (other.numerator == 0) {
// HINT: Division is multiplication by reciprocal throw new IllegalArgumentException("Cannot divide by zero");
// Don't forget to check if other.numerator is zero! }
return null; // Remove this line when implemented int newNumerator = this.numerator * other.denominator;
int newDenominator = this.denominator * other.numerator;
return new Rational(newNumerator, newDenominator);
} }
// TODO: Static method - r1 / r2
public static Rational divide(Rational r1, Rational r2) { public static Rational divide(Rational r1, Rational r2) {
// YOUR CODE HERE return r1.divide(r2);
return null; // Remove this line when implemented
} }
// PROVIDED - String representation
@Override @Override
public String toString() { public String toString() {
if (denominator == 1) { if (denominator == 1) {
@@ -101,7 +88,6 @@ public class Rational {
return numerator + "/" + denominator; return numerator + "/" + denominator;
} }
// PROVIDED - Decimal value
public double toDouble() { public double toDouble() {
return (double) numerator / denominator; return (double) numerator / denominator;
} }
+2 -1
View File
@@ -101,8 +101,9 @@ public class RationalTest {
try { try {
Rational zero = new Rational(0, 1); Rational zero = new Rational(0, 1);
Rational divisionByZero = r1.divide(zero); Rational divisionByZero = r1.divide(zero);
} catch (ArithmeticException e) { } catch (IllegalArgumentException e) {
System.out.println("Caught division by zero: " + e.getMessage()); System.out.println("Caught division by zero: " + e.getMessage());
} }
} }
} }
+5 -4
View File
@@ -21,15 +21,16 @@ public class Main {
break; break;
case 2: case 2:
// TODO: Get genre ID and page from user, then call movieService.displayMoviesByGenre()
Long genreId = getLongInput("Enter Genre ID: ");
Long page = getLongInput("Enter Page number: ");
movieService.displayMoviesByGenre(genreId, page);
break; break;
case 3: case 3:
// TODO (BONUS): Get movie ID from user, then call movieService.displayMovieDetails()
Long movieId = getLongInput("Enter Movie ID: ");
movieService.displayMovieDetails(movieId);
break; break;
case 0: case 0:
+101 -11
View File
@@ -1,24 +1,114 @@
package movie.apis; package movie.apis;
import com.google.gson.annotations.SerializedName;
import java.util.List; import java.util.List;
/**
* Model class representing a movie
* Fields: id, title, genres, images
*/
public class Movie { public class Movie {
private Long id; private Long id;
private String title; private String title;
private List<String> genres;
private List<String> images;
private String year; private String year;
private String imdb_rating;
private String country; private String country;
// TODO: Create a constructor with all fields // استفاده از SerializedName برای تطبیق دقیق با کلیدهای JSON
@SerializedName("imdb_rating")
private String imdbRating;
// TODO: Create a simple constructor with id and title only @SerializedName("imdb_votes")
private String imdbVotes;
// TODO: Create getters and setters for all fields private String director;
private String actors;
private String plot;
private String awards;
private String rated;
private String runtime;
private List<String> genres;
private List<String> images;
private String metascore;
@SerializedName("imdb_id")
private String imdbId;
public void setImdbRating(String imdbRating) {
this.imdbRating = imdbRating;
}
private String released;
private String type;
private String writer;
// Constructor کامل
public Movie(Long id, String title, String year, String country, String imdbRating, String imdbVotes,
String director, String actors, String plot, String awards, String rated, String runtime,
List<String> genres, List<String> images) {
this.id = id;
this.title = title;
this.year = year;
this.country = country;
this.imdbRating = imdbRating;
this.imdbVotes = imdbVotes;
this.director = director;
this.actors = actors;
this.plot = plot;
this.awards = awards;
this.rated = rated;
this.runtime = runtime;
this.genres = genres;
this.images = images;
}
// Constructor ساده
public Movie(Long id, String title) {
this.id = id;
this.title = title;
}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getYear() { return year; }
public void setYear(String year){ this.year = year;}
public String getCountry() { return country; }
public void setCountry(String country) { this.country = country; }
public List<String> getGenres() { return genres; }
public void setGenres(List<String> genres) { this.genres = genres; }
public List<String> getImages() { return images; }
public void setImages(List<String> images) { this.images = images; }
public String getMetascore() { return metascore; }
public void setMetascore(String metascore) { this.metascore = metascore; }
public String getImdbId() { return imdbId; }
public void setImdbId(String imdbId) { this.imdbId = imdbId; }
public String getReleased() { return released; }
public void setReleased(String released) { this.released = released; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public void setImdbVotes(String imdbVotes) {
this.imdbVotes = imdbVotes;
}
public String getWriter() { return writer; }
public void setWriter(String writer) { this.writer = writer; }
public String getImdbRating() { return imdbRating; }
public String getImdbVotes() { return imdbVotes; }
public String getDirector() { return director; }
public String getActors() { return actors; }
public String getPlot() { return plot; }
public String getAwards() { return awards; }
public String getRated() { return rated; }
public String getRuntime() { return runtime; }
public String getGenre() { return genres != null ? String.join(", ", genres) : "N/A";
}
} }
+41 -70
View File
@@ -87,104 +87,75 @@ public class MovieService {
} }
} }
/**
* TODO 1: Display movies for a specific genre and page
*
* Open this link in your browser (and check Pretty-print checkbox) to view json format:
* https://api.meshcomp.ir/api/v1/genres/1/movies
*
* Steps:
* - Call getMoviesByGenreList(genreId, page) to get JSON
* - Parse JSON to JsonObject
* - Get "movies" array (NOT "data")
* - Loop through array and print: "ID: {id} | {title} ({year})"
* - Also print total and total_pages
*
* PUT ALL PARSING CODE INSIDE try-catch
*/
public void displayMoviesByGenre(Long genreId, Long page) { public void displayMoviesByGenre(Long genreId, Long page) {
// TODO: Write your code here
// All parsing code must be inside try-catch
try { try {
// Your code here // ۱. گرفتن داده از API
String jsonResponse = getMoviesByGenreList(genreId, page);
if (jsonResponse == null) return;
// ۲. تبدیل به شیء JSON
JsonObject root = JsonParser.parseString(jsonResponse).getAsJsonObject();
JsonArray moviesArray = root.getAsJsonArray("movies");
// ۳. تبدیل JSON به لیست اشیاء Movie
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Movie>>(){}.getType();
List<Movie> movies = gson.fromJson(moviesArray, listType);
// ۴. چاپ لیست
for (Movie m : movies) {
System.out.println("ID: " + m.getId() + " | " + m.getTitle() + " (" + m.getYear() + ")");
}
// ۵. چاپ متادیتا
System.out.println("Total: " + root.get("total").getAsInt() +
" | Total Pages: " + root.get("total_pages").getAsInt());
} catch (Exception e) { } catch (Exception e) {
System.err.println("ERROR: " + e.getMessage()); System.err.println("ERROR: " + e.getMessage());
} }
} }
/** /**
* BONUS: Fetch movie details from API using movie ID * BONUS: Fetch movie details from API using movie ID
* URL format: https://api.meshcomp.ir/api/v1/movies/{movieId} * URL format: https://api.meshcomp.ir/api/v1/movies/{movieId}
*/ */
private String getMovieById(Long movieId) { private String getMovieById(Long movieId) {
try { try {
// TODO: Complete this method String url = MOVIE_BY_ID_URL + movieId;
// String url = MOVIE_BY_ID_URL + movieId; HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();
// HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// if (response.statusCode() == 200) return response.body();
return null; if (response.statusCode() == 200) return response.body();
} catch (Exception e) { } catch (Exception e) {
System.out.println("!!Exception : " + e.getMessage()); System.out.println("!!Exception : " + e.getMessage());
} }
return null; return null;
} }
/*
BONUS TODO: Display complete movie details for a given movie ID
Open this link in your browser (and check Pretty-print checkbox) to view json format:
https://api.meshcomp.ir/api/v1/movies/1
INSTRUCTIONS:
1. Call getMovieById(movieId) to get the JSON response string
2. Check if response is null (if yes, print error and return)
3. Parse the JSON string to JsonObject (inside try-catch)
4. Use Gson to extract all fields from the JSON and map them to your Movie class:
- Add missing JSON fields to your Movie class first (actors, awards, director,
imdb_id, imdb_votes, metascore, plot, rated, released, runtime, type, writer)
- Then use Gson to parse your json string
5. Print all movie details in a readable format
(PUT ALL PARSING CODE INSIDE THE EXISTING try-catch)
*/
/* EXAMPLE OUTPUT:
=======================================================================
THE SHAWSHANK REDEMPTION (1994)
=======================================================================
Rating: 9.3/10 | Votes: 1,738,596
Director: Frank Darabont
Cast: Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler
Genre: Crime, Drama
Runtime: 142 min | Rated: R
Country: USA | Released: 14 Oct 1994
Plot: Two imprisoned men bond over a number of years, finding
solace and eventual redemption through acts of common decency.
Awards: Nominated for 7 Oscars. Another 19 wins & 30 nominations.
=======================================================================
*/
public void displayMovieDetails(Long movieId) { public void displayMovieDetails(Long movieId) {
// Step 1: Get JSON response from API
String jsonResponse = getMovieById(movieId); String jsonResponse = getMovieById(movieId);
// Step 2: Check if we got valid data
// Step 3-5: Parse JSON and display details (PUT YOUR CODE INSIDE try-catch)
if (jsonResponse == null) { if (jsonResponse == null) {
System.out.println("Failed to get movie details for ID: " + movieId); System.out.println("Failed to get movie details for ID: " + movieId);
return; return;
} }
try { try {
// TODO: Parse jsonResponse to JsonObject Gson gson = new Gson();
// HINT: Use JsonParser.parseString(jsonResponse).getAsJsonObject() // تبدیل JSON به آبجکت Movie
// TODO: use Gson to parse the json Movie m = gson.fromJson(jsonResponse, Movie.class);
// Your code here:
// چاپ با فرمت خواسته شده
System.out.println("=======================================================================");
System.out.println(" " + m.getTitle().toUpperCase() + " (" + m.getYear() + ")");
System.out.println("=======================================================================");
System.out.println("Rating: " + m.getImdbRating() + "/10 | Votes: " + m.getImdbVotes());
System.out.println("Director: " + m.getDirector());
System.out.println("Cast: " + m.getActors());
System.out.println("Genre: " + m.getGenre());
System.out.println("Runtime: " + m.getRuntime() + " | Rated: " + m.getRated());
System.out.println("Plot: " + m.getPlot());
System.out.println("Awards: " + m.getAwards());
System.out.println("=======================================================================");
} catch (Exception e) { } catch (Exception e) {
System.err.println("ERROR parsing movie details: " + e.getMessage()); System.err.println("ERROR parsing movie details: " + e.getMessage());
} }