Java一段简单的代码,最好带上讲解~本人菜鸟

2025-03-14 00:08:36
推荐回答(4个)
回答1:

public static int sumSome(int position,int max){
int params[] = new int[]{4,3,5,8,5,3,1,5,1,8,0,6}; //读入的一串整数
int total = 0; //总和
for (int i = 0; i < params.length; i++) {
if((i+1)%position == 0){ //如果能整除postion,因为数组是从0开始,所以要加1
total += params[i];
}
}

return total;
}

回答2:

  import java.util.ArrayList;
  import java.util.Scanner;
  public class Main {
  public static void main(String[] args) {
      System.out.println(sumSome(3,10));
  }
  public static int sumSome(int position, int max) {
      int value = 0;
      ArrayList list = new ArrayList();
            
        //Take input from keyboard
      Scanner scan = new Scanner(System.in);
      while(scan.hasNextInt()) {
          list.add(scan.nextInt());
      }
        //Entering any letters rather than int numbers will end while loop above.
      System.out.println(list);
        //arraylist are indexed from 0, this is the reason i = position - 1
      for(int i = position - 1; value < max; i += position) {
          value += list.get(i);
      }
          return value;
      }
  }
/**
Now think what if the number of ints you have entered is quited limited,and quite a large max is considered, then Exception will occur. Solution:Add Try Catch.
**/
    try {
      for(int i = position - 1; value < max; i += position) {
          value += list.get(i);
      } catch (Exception e){
          System.out.println(e);
          System.out.println("value is constantly smaller than max");
      }

回答3:

public static int sumSome(int pos,int max){
int[] args = {4,3,5,8,5,4,1,5,1,8,0,6,4,3,5,8,5,4,1,5,1,8,0,6,4,3,5,8,5,4,1,5,1,8,0,6,4,3,5,8};
int total = 0;

/**
* 数组下标从0开始,所以(pos - 1)
* 每次获取下标为 pos+pos的值,所以 i += pos
*/
for(int i = (pos - 1); i < args.length; i += pos){
total += args[i];
if(total > max){
break;
}
}
return total;
}

回答4:

public static int sumSome(int pos,int max, int ...args){
int result = 0;
for(int i = (pos - 1); i < args.length; i += pos){
result = result + args[i];
if(result > max){
break;
}
}

return result;
}