0

I wanted help in regards to accessing the index then printing it. Below is the example and my desired output:

Input Format:

-Array Size

-string

-index to be printed

Input:

3 
Joana
Kim
Nina
2

Desired Output:

Your friends are:
Joana
Kim
Nina
Your best friend is:
Nina

This is the code I made. The third input format is not satisfied as I am yet to figure out the code to determine the bestfriend. How should I code to get the index from the given value?

 int words=input.nextInt();
String[] names=new String[words];

for(int counter=0;counter<words; counter++){
    names[counter]=input.next();
}
System.out.println("Your friends are");
for(int counter=0;counter<words;counter++){
    System.out.println(names[counter]);
1
  • 1
    You already do what you are asking "accessing the index then printing it" is names[counter]. So if you just want to check for the best friend names[number_for_bestfriend] number_for_bestfriend being the last number on your input that you have to get. Commented Jul 8, 2021 at 9:51

2 Answers 2

1

After getting all the friends, you have to take best friend index and print that.

int words=input.nextInt();
String[] names=new String[words];
for(int counter=0;counter<words; counter++){
    names[counter]=input.next();
}
int bestFriendIndex =input.nextInt();

System.out.println("Your friends are");
for(int counter=0;counter<words;counter++){
    System.out.println(names[counter]);
}

System.out.println("Your best friends is");
System.out.println(names[bestFriendIndex]);
Sign up to request clarification or add additional context in comments.

Comments

0
 import java.util.*;
class Demo{
public static void main(String args[]){
Scanner input=new Scanner(System.in);
int totfriend=input.nextInt();
String[] names=new String[totfriend];
for(int count=0;count<names.length; count++){
    names[count]=input.next();
}
int bestFriendIndex =input.nextInt();
for(String name : names){
            System.out.println(name);
        }
System.out.println(names[bestFriendIndex]);
}
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.