Hi, I have two homework questions for JAVA that I am stuck on and I was wonderin
ID: 674168 • Letter: H
Question
Hi, I have two homework questions for JAVA that I am stuck on and I was wondering if anyone can help me out, thanks! The first question wants me to write a static method that inputs an array of ints p and a String s. For each of the ints n in p, the method builds the substring consisting of the first n characters in s (or the whole of s, if n is greater than the length of s). The method returns the array of these substrings.
For example: stringHeads( new int[] { 3, 2, 5, 52, 0 }, "seventeen" ) returns the String array { "sev", "se", "seven", "seventeen", "" }.
The second question would be to write a static method called bothStart that allows the user to input two Strings and returns the String that is the longest substring s such that both inputs start with s.
For example,
bothStart( "radar dish", "radical food" ) returns "rad"
bothStart( "radar disk", "disk radar" ) returns ""
bothStart( "radar installation", "" ) returns ""
bothStart( "Mendacious", "Mendicant" ) returns "Mend"
bothStart( "FRANKLY", "frank" ) returns ""
Can you please help me write the code out with comments so I can study it? thanks!
Explanation / Answer
class substr
{
public static void main(String args[])
{
int a[]={3,2,5,52,0},i;
String str[] = new String[5];
for(i=0;i<5;i++)
{
str[i]=stringHeads(a[i], "seventeen");
}
//int i;
for(i=0;i<5;i++)
{
System.out.println(str[i]);
}
}
public static String stringHeads(int a ,String s)
{
String ss[]=new String[5];
int i;
if (a>s.length())
a=s.length();
return s.substring(0,a);
//return ss;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.