In: Computer Science
IN JAVA
Write a program with a method that returns an array. The method should accept as input a comma-delimited string with three values from a user. The array should store each value in a different element. Use Try..Catch error handling and print any failure messages, or print success from within method if the execution is successful (see Chapter 13 in the text). Call the method from the main method of the program to demonstrate its functionality by looping through the array and printing the individual values.
public class ArrayExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//reading string
System.out.println("Enter 3 values separated by comma
: ");
String str=sc.nextLine();
//calling metho to get array
int arr[]=getArray(str);
//printing array
for(int x:arr)
System.out.println(x);
}
private static int[] getArray(String arr) {
int res[]= new int[3];
int i=0;
//splitting the array
for(String s:arr.split(",")){
try{
//converting into int a
res[i++]=Integer.parseInt(s);
}catch(Exception e){}
}
return res;
}
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me