/** * q1: Write a public static method named q1 that takes an ArrayList of type
ID: 3718658 • Letter: #
Question
/**
* q1: Write a public static method named q1 that takes an ArrayList of type String and
* returns an int. This method returns the *index of* the shortest String among the values
* of the input
*/
/**
* q2: Write a public static method named q2 that takes an ArrayList of Doubles as a
* parameter and returns an ArrayList of Doubles. The returned ArrayList will contain only
* the values from the input ArrayList that have a cube root within 2.0 of 3.04 (ie. the
* target value of the cube root is 3.04 and the allowed variance from this target is 2.0)
*/
PLEASE USE JAVA.
Explanation / Answer
Java program to the given question:
import java.util.ArrayList;
public class Test
{
public static void main(String[] args)
{
//array list of strings
ArrayList<String> list= new ArrayList<String>();
//adding strings to list
list.add("Java");
list.add("javascript");
list.add("C#");
list.add("Perl");
list.add("C");
list.add("HTML");
//calling method q1() and assiging returning value to index variable
int index=Test.q1(list);
//displaying index
System.out.print("index="+index);
}
//method implementation
public static int q1(ArrayList<String> list)
{
//lets assume 1st index have string having small length
int flen=list.get(0).length();
int index=0;
//loop to travese the list
for(int i=0;i<list.size();i++)
{
//getting each string lenght in the arraylist
int len=list.get(i).length();
//comparing lenghts
if(len<flen)
{
//if less then the current lenght
index=i;
flen=len;
}
}
//returning index value to main method
return index;
}
}
Output: index=4
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.