Java2022期末作业
约 113 个字 69 行代码 预计阅读时间 1 分钟
Problem 1
Define a Java method to print the number of vowel character and the number of spaces in a given string.
Vowels include a,A,e,E,i,I,o,O,u,U.
code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedTransferQueue;
public class java2022 {
public static void main(String[] args) {
System.out.println(count("loveislove1 "))
}
public static int count(String str){
int tab = 0;
int vowel = 0;
for(int i = 0;i<str.length();i++){
char letter = str.charAt(i);
switch (letter) {
case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' -> vowel += 1;
}
if (letter == ' ') {
tab += 1;
}
}
return tab;
}
description
i defined a function which called count.First we using the String.charAt()
method to traverse the whole string.Then use switch
to judge if this is a vowel character.
Problem 2
Define a method to collect the common elements in two arrays of integers. int[] getCommonElements(int[] arr1, int[] arr2)
code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.LinkedTransferQueue;
public class java2022 {
public static void main(String[] args) {
int[] arr1 = {2,1,3,4,56};
int[] arr2 = {3,4,5};
System.out.println(Arrays.toString(getCommonElements2(arr1,arr2)));
}
public static int[] getCommonElements(int[] arr1, int[] arr2){
int maxlength = Math.max(arr1.length,arr2.length);
int arr[] = new int[maxlength];
int k = 0;
for(int i = 0;i<arr1.length;i++){
for(int j = 0;j<arr2.length;j++){
if(arr1[i] == arr2[j]){
arr[k++] = arr1[i];
break;
}
}
}
return arr;
}
public static int[] getCommonElements2(int[] arr1, int[] arr2){
int maxlength = Math.max(arr1.length,arr2.length);
int arr[] = new int[maxlength];
int k = 0;
Arrays.sort(arr1);
for(int i = 0;i<arr1.length;i++){
if(Arrays.binarySearch(arr2,arr1[i])>-1){
arr[k++] = arr1[i];
}
}
// //System.out.println(arr[]);
// System.out.println(Arrays.binarySearch(arr2,arr1[3]));
return arr;
}
}
description
in the problem i define two methods:one is the most common,the other use the Java Array
static method binarySearch
and sort
.