Emi
Emi

Reputation: 19

How to find index of string in java array from the given value?

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]);

Upvotes: 0

Views: 58

Answers (2)

Imesh Isuranga
Imesh Isuranga

Reputation: 39

 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]);
}
}

Upvotes: 0

Vimit Dhawan
Vimit Dhawan

Reputation: 677

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]);

Upvotes: 1

Related Questions