Get Element By Index

Didn't understand the main method and O/P. Can anyone help me to understand the main method? and print statements also didn't understand.

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(){
    return topics[0];
  }
  
  public void viewTopic(int topicIndex){
    views[topicIndex] = views[topicIndex] + 1;
  }

  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!"); 
  }
}

O/P: 
The top topic is Opinion
The Tech topic has been viewed 3 times!

What specifically do you not understand? Try what I suggested in your last post, walking through the code line by line.

Why we are calling viewTopic method that many times? and how it’s behaving ?

You’re calling the viewTopic function that many times just to simulate viewing a topic. Count the number of times you view the topic at index 1. Does it match the number given in the output?

1 Like

I don’t think it’s matched but that was the output I got it but I am not sure.

How many times have you used 1 as the argument of the viewTopic function in the code above? Add that to the starting value at index 1 of view topics.

public void viewTopic(int topicIndex){
    views[topicIndex] = views[topicIndex] + 1;

I am passing 3 times but I didn't understand how it's calculating ?
Ex : when we pass first time the calculation is below 

public void viewTopic(int 1){
    views[1] = views[1] + 1;

So what is the result of this ? if the result is 2 for that when we pass second time the result should be 3 but we are passing 3 times right? the output should "viewed 4 times" but got 3 times

If my understanding is wrong please correct me 

What is the initial value at index 1 of the views array? What. happens when you add three to that?

I am assuming the below is the initial value at index 1 I mean zero

public class Newsfeed {
  
  String[] topics = {"Opinion", "Tech", "Science", "Health"};
  int[] views = {0, 0, 0, 0};

if it is right if I add 3 I think the output will be 4 

Correct me if I am wrong

Yes, the initial value here is zero/0.

No. 0+3≠4. 0+3 equals 3, which is the output.

Got it thank you so much: smile:

1 Like