#java #methods
#java #методы
Вопрос:
Я очень новичок в программировании, и одним из моих проектов было создание двух книг с именем, автором, названием и т. Д. Проблема в том, что мне нужно дать каждой книге как минимум случайные 5 оценок (0-5 звезд), используя метод добавления рейтинга, предоставляемый классом (первый набор кода). Я не уверен, как подойти к этому, чтобы присвоить каждой книге рейтинг. Конечно, первая книга (book1) является конструктором по умолчанию, поэтому (book2) нуждается в случайных оценках.
public class Book {
private String title;
private String author;
private int numPages;
private double avgRating;
private int ratingCount;
/*
*Creates a book with default values
*/
public Book(){
title = "Something";
author = "Anonymous";
numPages = 1000;
avgRating = 1.0;
ratingCount = 1;
}
/*
*Creates a book with the given values
*parameter bTitle - title of the book
*parameter bAuthor - author of the book
*parameter pages - how many pages are in the book
*parameter bRating - the book's average rating, out of 5 stars
*parameter rCount - how many ratings the book has
*/
public Book(String bTitle, String bAuthor, int pages, double bRating, int rCount) {
title = bTitle;
author = bAuthor;
numPages = pages;
avgRating = bRating;
ratingCount = rCount;
}
/*
*returns the author of this book as a String
*/
public String getAuthor() {
return author;
}
/*
*returns the title of this book as a String
*/
public String getTitle() {
return title;
}
/*
*returns the pages of this book as an int
*/
public int getPages() {
return numPages;
}
/*
*returns the rating of this book as a double
*/
public double getRating() {
return avgRating;
}
public int getRatingCount() {
return ratingCount;
}
public void addRating(int stars){
//calculate total of all ratings
double total= avgRating * ratingCount;
//increase number of ratings to include this new one
ratingCount ;
//add this rating to the total of all ratings
total = stars;
//recalculate average
avgRating = total / ratingCount;
}
}
import java.util.Scanner;
public class Project2{
public static void main(String[] args){
/*
*Asks the user for title of the book
*Asks the user for author of the book
*Asks the user for the number of pages of the book
*/
Scanner type = new Scanner(System.in);
System.out.print("Give the title of a book: ");
String title = type.nextLine();
System.out.print("Enter the author of " title ": ");
String author = type.nextLine();
System.out.print("Enter the number of pages in " title ": ");
int numPages = type.nextInt();
Book book1 = new Book();
Book book2 = new Book(title, author, numPages, avgRating, ratingcount);
//Combines both The last letter of each book's title//
int totalCharacter = book1.getTitle().length() book2.getTitle().length();
System.out.println("Book1 title is: " book1.getTitle() "." " It was written by " book1.getAuthor() " and has " book1.getPages() " pages." " After " book1.getRatingCount() " ratings, this book got a rating of " book1.getRating() ".");
System.out.println("Book2 title is: " book2.getTitle() "." " It was written by " book2.getAuthor() " and has " book2.getPages() " pages." " After " book2.getRatingCount() " ratings, this book got a rating of " book2.getRating() ".");
System.out.println("The total number of characters in both books title is: " totalCharacter);
System.out.println("The first letter of each author's name, concatenated together is: " book1.getAuthor().substring(0,1) book2.getAuthor().substring(0,1));
System.out.println("The last letter of each book's title, concatenated together is: " book1.getTitle().substring(book1.getTitle().length()-1) book2.getTitle().substring(book2.getTitle().length()-1));
}
}
Комментарии:
1. вы не можете сделать это с помощью цикла for?
2. У вас ошибки компиляции.
Ответ №1:
Book book2 = new Book(title, author, numPages, avgRating, ratingcount);
Вы используете переменные, которые не объявлены. avgRating, ratingCount
. Сначала объявите их. Если вы хотите дать некоторый случайный рейтинг, вы можете использовать Math.random()
метод, который дает случайное double
значение от 0 до 1. Умножьте его на число, чтобы получить желаемый рейтинг.
При создании книги вы даете только начальную оценку (значения). Каждая книга создается с начальным рейтингом, как указано в вашем конструкторе по умолчанию.
При создании книги со вторым конструктором вы можете передать значения, которые указаны как в самом вашем конструкторе по умолчанию.
Book book2 = new Book(title, author, numPages, 1.0, 1);
или некоторые другие значения по вашему выбору.
Вы добавляете рейтинг после создания книги, для которой у вас есть addRating()
метод, позволяющий добавлять свои рейтинги, которые автоматически вычисляют средний рейтинг вашей книги.
book1.addRating(4);
book2.addRating(5);
Кроме того, вам также следует написать getAvgRating()
метод, который возвращает avgRating
Комментарии:
1. Большое вам спасибо! Я ценю это!
Ответ №2:
Возможные решения:
- Math.random() был бы самым простым способом получить случайные числа (также может быть выполнено в пределах диапазона)
- Определите и используйте переменные, необходимые соответствующим образом, иначе это приведет к нулевому исключению