How to write a Java program that evaluates two strings tosee if they contain the
ID: 3613494 • Letter: H
Question
How to write a Java program that evaluates two strings tosee if they contain the same
integers with the same multiplicities, but without regardto order. For example,
suppose you have the two strings 66 88 110 66 40 and 40 6666 88 110. These
strings contain the same integers both contain twoinstances of 66, one instance
of 40, one instance of 88, and one instance of 110 (eventhough theyre not in
public static int[] stringToArray(String s)This methodshould take
a string as a parameter and return an array of the integerscontained in that
string. The method should work even if the string containsinvalid integers.
Invalid integers should simply be skipped. Example: if theparameter were the
string Java 89 is 3.14 so 7 fun!", the method shouldreturn the array [89 7].
Hint: use the parseIntmethod ofthe Integer class, and catch its Number-
FormatException.
public static boolean containSameElements(int[] a, int[]b) This
method should take two integer arrays as parameters andreturn true or false
depending on whether they contain the same elements, asdiscussed above. Note
1
that the arrays might not be the same size in this case,the method should ob-
viously return false. Do NOT sort the arrays as part ofyour solution.
public static void main(String[] args)The mainmethod should call
stringToArray on some strings,call containSameElements() on theresult-
ing arrays, and display the result(true or false). You can specify your strings
directly in the main() method (no need toread from le). Include at least
two pairs of strings in your main() method one pair that contain thesame
elements, and one pair that do not.
Explanation / Answer
publicstatic int[] stringToArray(String input) { // split string byspaces String[] split= input.split(""); // find number ofintegers that can be parsed. int count= 0; // try to parse stringsin split for(int i = 0; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.