In: Computer Science
1. Write a Java program from scratch that meets the following requirements:
a. The program is in a file called Duplicates.java that defines a class called Duplicates (upper/lower case matters)
b. The program includes a Java method called noDuplicates that takes an array of integers and returns true if all the integers in that array are distinct (i.e., no duplicates). Otherwise it returns false. Make sure the method is public static.
example tests: noDuplicates({}) returns true
noDuplicates({-1, 1}) returns true noDuplicates({4,22,100,99,1,5,7}) returns true
noDuplicates({4,22,100,99,22,5,7}) returns false
c. The program’s main method calls noDuplicates on the above test cases and prints each return value.
2. Write a Java program from scratch that meets the following requirements:
a. The program is in a file called Matching.java that defines a class called Matching.
b. The program includes a Java method called find that takes two Strings and returns an integer. If the second string does not appear in the first string, find returns -1. If the second string appears in the first string, find returns the index of the character where the second string begins in the first string. Make sure the method is public static.
example tests:
find("","") returns 0
find("", "a") returns -1
find("Hello World", "World") returns 6
find("World", "Hello World") returns -1
code:
public static boolean noDuplicates(int[] numbers){
for(int i=0;i<numbers.length;i++){
for(int j=i+1;j<numbers.length;j++){
if(numbers[i]==numbers[j]){
return false;
}
}
}
return true;
}
public static int find(String s1,String s2){
return s1.indexOf(s2);
}
public static void main(String[] args) {
System.out.println(noDuplicates(new int[] {}));
System.out.println(noDuplicates(new int[] {-1, 1}));
System.out.println(noDuplicates(new int[] {4,22,100,99,1,5,7}));
System.out.println(noDuplicates(new int[] {4,22,100,99,22,5,7}));
System.out.println(find("",""));
System.out.println(find("", "a"));
System.out.println(find("Hello World", "World"));
System.out.println(find("World", "Hello World"));
}