1、将一个数组逆序输出
public class Test4 {
public static void main(String[] args) {
int[] arr = {2,4,3,8,6};
for (int i = arr.length - 1;i >= 0;i--){
System.out.println(arr[i]);
}
}
}
2、求一个数组所有元素的总和
public class Test {
public static void main(String[] args) {
int[] arr = {10,10,4,20,16};
int sum = 0;
for(int i = 0;i < arr.length;i++){
int element = arr[i];
sum = sum + element;
}
System.out.println(sum);
}
}
3、求数组中的偶数元素以及所有偶数的总和
public class Test {
public static void main(String[] args) {
int[] arr = {10,7,31,4,5,104,16};
int sum = 0;
System.out.print("{");
for(int i = 0;i < arr.length;i++){
int element = arr[i];
if(element % 2 == 0){
sum = sum + element;
System.out.print(element);
if (i != arr.length - 1){
System.out.print(",");
}
}
}
System.out.println("}");
System.out.println("数组中偶数总和为:" + sum);
}
}
4、求一个数组元素的最大值和最小值以及最大值与最小值的差值
public class Test3 {
public static void main(String[] args) {
int[] array = {1,-1016,1004,50,101};
int max = array[0];
int min = array[0];
for (int i = 0;i < array.length;i++){
if(max <= array[i]){
max = array[i];
}
if (min >= array[i]){
min = array[i];
}
}
System.out.println("数组中的最大值为:" + max);
System.out.println("数组中的最小值为:" + min);
System.out.println("最大值与最小值的差值:" + (max-min));
}
}
5、将一个数组中的元素逆置输出
public class Test {
public static void main(String[] args) {
int[] arr = {1,3,1,4,5,2,0};
for (int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
int len = arr.length;
for (int i = 0;i< len / 2;i++){
int temp = arr[i];
arr[i] = arr[len - i - 1];
arr[len - i -1] = temp;
}
for (int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
}
}
6、求一个字符串数组中所有字符的个数
public class Test5 {
public static void main(String[] args) {
String[] strArray = {"sdrfg","bjkl","ncmft","tgyh","hkuk"};
int sum = 0;
for(int i = 0;i < strArray.length;i++){
String temp = strArray[i];
int length = temp.length();
sum = sum + length;
}
System.out.println(sum);
}
}