intro programming on java with compareTo [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
just got some computer science from my friend, I believe it is a intro to programming assignment, and I was trying on it, but it seems there are so many issue, seems I am majoring CS, can someone help me on those questions step by step, would be appreciated. in instructions are following:
Create a public class Movie with private instance variables String title
and int year. The class should declare that it implements the
Comparable interface, and should provide the following:
• A constructor that takes 2 arguments: a String and an int (in that order)
for initializing title and year.
• A method that satisfies the Comparable interface. Movies should be compared first by title and then by year.
{ The Maltese Falcon 1941, The Thomas Crown Affair 1968, The Thomas Crown Affair 1999}
An equals() method that is compatible with the method that satisfies the
Comparable interface.
• A toString() method that prints “Movie” followed by 1 space followed by
the title followed by 1 space followed by open-parenthesis followed by
the year followed by close-parenthesis. Example:
The Maltese Falcon (1941)
• A public static method getTestMovies(), which returns an array of 10
unique Movie instances. The 0th and 1st array elements must be 2 movies
with the same title but from different years (e.g. The Thomas Crown
Affair 1968 and The Thomas Crown Affair 1999, or True Grit 1969 and
True Grit 2010). The 2nd and 3rd elements must 2 movies with different
titles but from the same year (e.g. The Martian 2015 and Bridge of Spies
2015). The 4th and 5th elements must be 2 different objects that
represent the same movie.
• A hashCode() method. Use the following:
public int hashCode()
{
return title.hashCode() + year;
}
the following is what I have so far, I have the constructor and the starter, but I am sure how to do it.
public class Movie implements Comparable<Movie>{
private String title;
private int year;
public Movie(String title, int year){
this.title = title;
this.year = year;
}
#Override
public int compareTo(Movie that) {
int value = 0;
if(this.title == that.title)
{
if(this.year < that.year){
value = 0;
}
else{
value = -1;
}
}
return value;
}
public static void getTestMovie(){
}
public boolean equals(Object x)
{
}
}
Any Helps are appreciated!

When you want sorting other than natural order, you should Comparator rather than Comparable. Please follow below link for more info :
What is the difference between compare() and compareTo()?
Regarding string comparison use str1.equals(str2). For the reason follow below link :
What is the difference between == vs equals() in Java?
For rest of the questions, please post some tried code.

You can't use this.title == that.title on Strings. You should use this.title.equals(that.title).
Except, for this code, you shouldn't. You should use this.title.compareTo(that.title).
If that return non-zero, return that value, because it represents the ordering when titles differ.
If it returned zero, the titles were equal, and you need the secondary check on year. For that use Integer.compare(this.year, that.year).

Related

How can I find capacity of stadium using Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This is the question
Write a method atCapacity(int people, int capacity) that returns a boolean determining if a stadium is at maximum capacity. A stadium is at capacity if at least 80% of the seats are sold out.
Here's the code I tried
public class Scratchpad
{
atCapacity(int people, int capacity)
{
boolean atCapacity = false;
capacity = people * (80/100);
if(people > capacity)
{
return false;
}
else if(people <= capacity)
{
return true;
}
}
}
The code checker says
"Grader.java: Line 4: invalid method declaration; return type
required"
I don't understand how to fix the code. I'm not asking for answers I just need a nudge in the right direction. Thanks
This is supposed to be a method declaration:
atCapacity(int people, int capacity)
But the syntax for a method declaration requires a return type, as in
SomeReturnType atCapacity(int people, int capacity)
If we look at the body of the method you are returning true and false so the correct type should be the type of true and false, which is <nudge>
I can see some other errors too (<nudges>):
The compiler will tell you that you need a return at the end of the method. (It is not going to deduce that people > capacity and people <= capacity are mutually exclusive.)
There is more than one way of solving that conundrum.
At runtime, 80/100 is going to cause you grief; see Int division: Why is the result of 1/3 == 0?.
On the top of that, you have a variable called atCapacity which doesn't appear to be needed.
you could write
public boolean atCapacity() { ... }

Limiting a function's input to specific integers [duplicate]

This question already has answers here:
Java Class Constructor Parameters with range limits
(3 answers)
Closed 5 years ago.
What is the best practice to limit a functions inputs to specific integers in java?
lets say
public Car(CarColor carcolor, (Range limited integer value) carnum) {
// Rest of the code
}
For strings the best way is to use enumeration like
enum CarColor{
Blue, Black, Red, Green
}
But it wont work for integers
enum CarNumber{
1,2,3,4,5
}
What i came up with is this:
enum CarNumber{
c1, c2, c3, c4, c5;
#Override
public String toString() {
return this.name().substring(1);
}
}
But I'm pretty sure this is not a good practice.
I also don't want to let the function be called by any integer and check with a if inside the function like below. The function should not be able to be called and limited with a enum like style.
public Car(CarColor carcolor, int carnum) {
if (carnum < 0 || carnum > 5)
return ;
// Rest of the code
}
Maybe your best bet is to make a class that only takes in a variable that is between a certain range and then only accept an instance of that class as a parameter in your function. This way, your function won't have to check anything because it already knows that it won't be outside of a range.

What is the best data structure that represents the following data type? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have data type of the following format:
Popularity:xx
Name:xx
Author:xx
Sales:xx
Date Published: xx
I am free to choose whatever way I can store my data in.
I will need to perform some queries on the data, for example
What are the top 'N' Books for the year 'M'
What are the average sales of the top 'N' songs for author 'X'?
It should be kept in mind that further queries may be added.
What will be the different ways to represent the data to perform the queries (in Java)? What will be the merits?
Note: (Not looking for a DB solution)
JDK comes bundled with Java DB and seems perfectly fine for your use case.
Edit: Sorry I misread the question as a dB solution because it seems you need it. That said you should look for a DB solution where you just query your books from.
If you actually do want to perform queries on data-structures in memory you can use Apache Commons Collections which support filtering.
If you do want to use a data-structure like a Vector which seems like a solution, you need to build indexes to improve performance. Then lookup in the indices and get the book needed. If you know which searches are necessary you can group chosen indexes and create a block to easily search. Essentially creating your own cube data-structure. Could be a nice project.
Arraylist of a class. Create a class with those variables as, well, class variables, then instantiate an Arraylist of said object. Then you can perform searches based on the values of certain variables. For example:
//replace "ClassName" with the name of the class
ArrayList<"ClassName"> array = new ArrayList<"ClassName">();
ArrayList<"ClassName"> results = new ArrayList<"ClassName">();
for("ClassName" obj:array)
{
if(obj.getAuthor().equals("Author Name"))
{
results.add(obj);
}
}
There are many ways to sort the results, including using Collections.sort(); which seems to be the best way to go about it.
Sort ArrayList of custom Objects by property
EDIT: I went ahead and gave you an example based on the specific case you outlined in the comments. This should help you out a lot. As stated before, I had a similar issue for a lab in University, and this was a way I did it.
You could use a Bean to wrap your data:
public class Record {
int popularity;
String name;
String author;
int sales;
int yearPublished;
public Record(int popularity, String name, String author, int sales, int yearPublished) {
super();
this.popularity = popularity;
this.name = name;
this.author = author;
this.sales = sales;
this.yearPublished = yearPublished;
}
//getter and setter...
public String toString(){
return name;
}
And this is a typical usage querying with java8:
Record Record1 = new Record(10,"Record 1 Title","Author 1 Record",10,1990);
Record Record2 = new Record(100,"Record 2 Title","Author 2 Record",100,2010);
Record Record3 = new Record(140,"Record 3 Title","Author 3 Record",120,2000);
Record Record4 = new Record(310,"Record 4 Title","Author 1 Record",130,2010);
Record Record5 = new Record(110,"Record 5 Title","Author 5 Record",140,1987);
Record Record6 = new Record(160,"Record 6 Title","Author 1 Record",15,2010);
Record Record7 = new Record(107,"Record 7 Title","Author 1 Record",4,1980);
Record Record8 = new Record(1440,"Record 8 Title","Author 8 Record",1220,1970);
Record Record9 = new Record(1120,"Record 9 Title","Author 9 Record",1123,2010);
List<Record> Records = Arrays.asList(Record1,Record2,Record3,Record4,Record5,Record6,Record7,Record8,Record9);
//top 2 record of year 2010
int m = 2;
int year = 2010;
System.out.println(Arrays.toString(Records.stream().filter(s -> s.getYearPublished() == year).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(m).toArray()));
//average top 2 record of Author 1 Record
String author= "Author 1 Record";
int n = 2;
System.out.println(Records.stream().filter(s -> author.equals(s.getAuthor())).sorted((r1, r2) -> Integer.compare(r2.popularity, r1.popularity)).limit(n).mapToInt(Record::getSales).average().getAsDouble());
This prints:
[Record 9 Title, Record 4 Title]
72.5
Having a collection of objects you can use stream api to collect/filter/reduce your results. There is not so much to it.
The main problem is to not load all of the objects to memory and to be able to retrieve them from whatever store efficiently by using indexes, reverse-indexes.
One of the frameworks which came to my mind is Apache spark

Best way to store temporary QuestionID-AnswerID data

I'm developing a quiz app and I want to find an efficient way to save user's answers.
Each quiz has 30 questions and all I need to save is:
questionNumber, questionId and answerId and either the answer is correct or not.
I thought an array will be a good solution. Example:
Each row represents a question (questionNumber). The first column represents the questionId and the second answerId. The third column will contain either 0 (incorrect) or 1 (correct).
The third column (correct) is needed to sum the number of correct answers (it's faster to sum the third column instead of checking each answer any time).
This isn't a SQL table - this info is temporary and will be destroyed as soon as the user finishes the quiz.
I want to know if you have any other solutions, maybe better.
Thank you!
Why not a class?
class Answer
{
private int questionID;
private int answerID;
private boolean correct;
public Answer(int questionID, int answerID, boolean correct)
{
this.questionID = questionID;
this.answerID = answerID;
this.correct = correct;
}
}
And an ArrayList
List<Answer> answers = new ArrayList<Answer>();
Then use
Answer answer = new Answer(1, 2, true);
answers.add(answer);
With an Array you will need to fix the array size every time you add a question with an ArrayList you can add as much questions as you want without care about the array size.
Anyway, if you questions will be always 30 you can create an Array too without problems.
About performances, well i don't see problems about speed/memory.

Sorting arrays with the same order

I'm making a program to make a list of people, with 3 different marks of time (in double)
To do it, I made 4 arrays, One String, to save people names, and 3 Doubles to save the 3 marks on the years 2010, 2011, and 2012.
In the menu, I have to implement an option to sort the list on 2012s mark, in descending order.
Like this
m12[0] = 12.1
m12[1] = 34.1
m12[2] = 23.1
m12[3] = 23.5
into:
m12[1] = 34.1
m12[3] = 23.5
m12[2] = 21.1
m12[0] = 12.1
I did it with a basic algorithm, but now I want to know if it's possible to get the actual order of the arrays, ([1],[3],[2],[0]) and apply it to the other arrays I have to print it as a list based on the 2012 mark in descending order.
Thats the code I have to make the normal order list:
if(option==2){
System.out.println("# , Name, 2010, 2011, 2012");
for(i=0;i<dorsal.length-1;i++){
if(dorsal[i]!=0){
System.out.println(dorsal[i]+"- "+nom[i]+", "+m10[i]+", "+m11[i]+", "+m12[i] );
}
}
System.out.println("Press ENTER to return");
intro.nextLine();
}
Sorry if I didnt explained it very good, I started programming 3 months ago and I'm so newbie.
//EDIT
I'll paste here the head of the exercise:
Thats exactly the programs needs to do. I'm stucked at point 3.
The objective is to develop a program to manage a list of members of
in a competition of long jump. The number of places available is 15.
Their data will be introduced in the same order in which the athletes
enroll. Design a program that shows the following options:
1 – Register a participant
2 – List all the participant’s data
3 – List all the participant’s data by mark
4 – Quit
If 1 is selected, data of one of the participants will be introduced:
Name, best mark in 2012, best mark in 2011 and best mark in 2010.
If 2 is selected, we have to list all participant’s data ordered by dorsal
number (the order they’ve enrolled)
If 3 is selected, we have to list all participant’s data ordered by 2012
mark, from greater to smaller.
After processing each option, the main menu must be shown again,
till the option 4 is selected, quitting the program.
Thanks.
Define a class to contain the data for each person, such as:
public class Person
{
private String name;
Private Map<Integer,Double> marks = new HashMap<Integer,Double>();
public Person(String name) { this.name = name; }
public void setMark(int year, double mark) {
this.marks.put(year,mark);
}
public void getMark(int year) {
// return zero if there's no mark for the requested year
return this.marks.containsKey(year) ? this.marks.get(year) : 0;
}
}
Then write a Comparator<Person>
public PersonComparatorOnMarkDescending implements Comparator<Person>
{
private int yearToCompare;
public PersonComparator(int yearToCompare) {
this.yearToCompare = yearToCompare;
}
public compare(Person p1, Person p2)
{
Integer p1Mark = p1.getMark(yearToCompare);
Integer p2Mark = p2.getMark(yearToCompare);
return p2.compareTo(p1);
}
}
You can then define a List<Person> or a Person[] array and use the sorting methods available in java.util. Instantiate the comparator with, for instance:
Comparator<Person> comp = new PersonComparatorOnMarkDescending(2012);
This approach lets you sort the collection on any year's marks.

Categories

Resources