- Start with this code:
import java.util.Arrays;
public class Newsfeed {
String[] topics = {"Opinion", "Tech", "Science", "Health"};
int[] views = {0, 0, 0, 0};
public Newsfeed(){
}
public String[] getTopics(){
return topics;
}
public String getTopTopic(){
}
public void viewTopic(int topicIndex){
}
public static void main(String[] args){
Newsfeed sampleFeed = new Newsfeed();
System.out.println("The top topic is "+ sampleFeed.getTopTopic());
sampleFeed.viewTopic(1);
sampleFeed.viewTopic(1);
sampleFeed.viewTopic(3);
sampleFeed.viewTopic(2);
sampleFeed.viewTopic(2);
sampleFeed.viewTopic(1);
System.out.println("The " + sampleFeed.topics[1] + " topic has been viewed " + sampleFeed.views[1] + " times!");
}
}
-
We have augmented the
Newsfeed
class to start with thetopics
array as an instance field.Fill in the
getTopTopic()
method to return the 0th index of thetopics
array. -
But wait — we added more to the
Newsfeed
class. Now, each instance starts with an array of zeros calledviews
as an instance field.Every time someone views a topic, we want to increment the value of the appropriate field in
views
.For example, if someone views an
"Opinion"
piece, we want to increase the value of the 0th index ofviews
from0
to1
. If they view it again, we want to increase the value to2
.We have written a method signature for
viewTopic()
, which takes in anint
calledtopicIndex
.Inside the method, set the value of the
views
array at the indextopicIndex
to the current value plus1
.
Example solution can be found in the Newsfeed.java file