Write a java program to find nth number word from the string

Write a java program to find nth number word from the string. Write a program to read a string that contains comma separated fruit names and also a number N. Pick the nth fruit and return it. If the total number of elements is less than the number specified in N, then return the last element.

Input and Output Format:

Input consists of a string and integer.
Output consists of a string.
Refer sample output for formatting specifications.

Sample Input 1:
Apple,Banana,Orange
2

Sample Output 1:
Banana

Sample Input 2:
Apple,Banana,Orange
4

Sample Output 2:
Orange

java program to find nth number word from the string

import java.util.Scanner;
import java.util.StringTokenizer;
 
public class Main
{
public static void main(String args[])
{
 
String str=new String();
Scanner sc=new Scanner(System.in);
str=sc.nextLine();
int n=sc.nextInt();
String k=findFruitName(str, n);
System.out.println(k);
 
}
 
 
public static String findFruitName(String m,int n)
{
int i=0;
String h=null;
StringTokenizer st=new StringTokenizer(m,",");
 
int max=st.countTokens();
String[] ss=new String[max];
while(st.hasMoreElements())
{
ss[i++]=st.nextToken();
}
if(n>max)
h=ss[i-1];
else
h=ss[n-1];
return h;
}

Add a Comment

Your email address will not be published. Required fields are marked *

20 − 19 =