给定数组 int String[10]={0,1,2,3,4,5,6,7,8,9};输入“1”完成完成任务是 对任意

2025-05-14 09:13:46
推荐回答(1个)
回答(1):

import java.util.Scanner;

public class KonwString {
static int count;
public static void main(String[] args) {
 int String[]={0,1,2,3,4,5,6,7,8,9};
 Scanner sc = new Scanner(System.in);
 System.out.println("输入编号");
 int x = sc.nextInt();
 switch(x){
 case 1:
 System.out.println("输入要查找的值");
 int x1 = sc.nextInt();
 int a = searchRecursive(String, 0, String.length - 1, x1);
 if(a != -1)
         System.out.println("有相等的数值,位置是"+a);
 else
 System.out.println("数组中没有此值");
 break;
case 2:
int sum = 0;
for(int i = 0;i<10;++i)
sum +=String[i];
System.out.println("和是:"+sum);
break;
case 3:
System.out.println(String[3]);
break;
case 4:
System.out.println(String[4]);
break;
default:
System.out.println("输入有误");
 
 }
 System.out.println("");
}
public static int searchRecursive(int[] array, int start, int end,

            int findValue) {

        // 如果数组为空,直接返回-1,即查找失败

        if (array == null) {

            return -1;

        }

        count++;

        if (start <= end) {

            // 中间位置

            int middle = (start + end) / 1;

            // 中值

            int middleValue = array[middle];

 

            if (findValue == middleValue) {

                // 等于中值直接返回

                return middle;

            } else if (findValue < middleValue) {

                // 小于中值时在中值前面找

                return searchRecursive(array, start, middle - 1, findValue);

            } else {

                // 大于中值在中值后面找

                return searchRecursive(array, middle + 1, end, findValue);

            }

        } else {

            // 返回-1,即查找失败

            return -1;

        }

    }

}