205k views
2 votes
Write a Java class with the following methods: getArray(int numStrings) is an instance method that takes command line input (use a Scanner's nextLine() method) to create an array of Strings whose length is numStrings and returns a reference to the array. getArray() does not print anything! getLongestString(String[] sArray) is an instance method that returns a reference to the longest String in sArray. getLongestString() does not print anything! main() creates an instance of the class and uses it to call getArray() with the argument 5, keeping a reference to the return value, then sends the array to getLongestString(), and prints the result

User Adesara
by
5.3k points

1 Answer

5 votes

Answer:

Follows are the code to this question:

import java.util.*;//import packae for user-input

public class Main//defining a class Main

{

public String[] getArray(int numString)//defining a method getArray

{

String[] name=new String[numString];//defining array of String values

Scanner in = new Scanner(System.in);// creating scanner class object for input values from user-end

for(int i=0;i<numString;i++)//defining for loop for input multiple values

{

System.out.print("Enter String Value :");//print message

name[i]=in.nextLine();//input values

}

return name;//return array values

}

public String getLongestString(String[] sArray)//defining a method getLongestString

{

int m=0,mi=0; //defining integer variables

for(int i=0;i<sArray.length;i++)//defining for loop for check the longest value in array

{

if(m<sArray[i].length())//defining if block that checks m varaible value greater then sArray length

{

m=sArray[i].length();//use m to hold sArray length

mi=i;//use max_index to hold i that is loop value

}

}

return sArray[mi];//return Longest value

}

public static void main(String[] args)//defining main method

{

Main s=new Main();//Creating object of main class

String[] n;//defining string variable n

n=s.getArray(5);//use n varaible to call getArray method and store its value

System.out.println("Longest value is: "+s.getLongestString(n));//use print method to call getLongestString method

}

}

Output:

please find attached file.

Step-by-step explanation:

In the given java program code, inside the main class two method that is "getArray and getLongestString", is defined, in which the "getArray" method uses an integer variable in its parameter and inside the method, an array is defined that use a scanner class for input array value.

  • In the "getLongestString" pass as a parameter and inside the method, two integer variable "m and mi" is defined that use in the loop to return the longest string value.
  • In the class main method is to define that creates a class object and call the above method and use the print method to return its value.
Write a Java class with the following methods: getArray(int numStrings) is an instance-example-1
User Jamal Eason
by
5.2k points