Write a method with the method header below. This method takes an array of Strin
ID: 3565775 • Letter: W
Question
Write a method with the method header below. This method takes an array of Strings and a position. The method should return the String at that position. For example, sending ["hello", "cat", "book", "California"] and 2 would return "book".
Use exception handling (with Java-provided exceptions) to account for and handle invalid positions. Your method should not crash under any circumstances.
public String getStringAt(String[] wordList, int position) {
// YOUR CODE HERE
}
This is what i have so far, please correct if you find any mistakes.
public String getStringAt(String[] wordList, int position){
try{
return wordList[position];
}
catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Input too short. Try again.");
}
return "";
}
Explanation / Answer
import java.util.Scanner;
public class expHandle {
public static void main(String Args[])
{
try
{
String[] S={"Shyam","ram","GHanshyam","Mahesh","Divyansh","micheal","denny","123","abc","xyz"};
System.out.println("Please enter the Position ");
Scanner in=new Scanner(System.in);
int num=in.nextInt();
getStringAt(S, num);
}
catch(Exception e)
{
System.out.println(e);
}
}
public static String getStringAt(String[] wordList, int position){
try{
return wordList[position];
}
catch(Exception ex){
System.out.println(ex);
}
return "";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.