-2

Q: 在main方法中获取开始和结束整数。将这两个值传递给一个单独的函数。返回这些值(包括)之间的所有数字,这些数字可以被 3 整除,从函数返回到主函数。 我已经完成了:

import java.util.*;
public class inbetween {
    public static void main (String[]args) {
        Scanner in = new Scanner (System.in);
        System.out.println("Enter range of values");
        int x =in.nextInt();
        int y =in.nextInt();
        search(x,y);

    }

    public static void search(int a, int b) {
          int length = (b-a)+1;
        int [] arr = new int [length];
        for(int i=0; i<length; i++)
        {
          a = a+1;
         int c;
         // int count=0;
          c = a%3;
          if (c==0) {
              arr[i] = a;
          System.out.println(arr[i]);
       //   count = count+1;
       //   return count;

        }
        }
    }
}

现在我的问题是..如何返回数组并在函数中打印并在那里打印???此代码有效,但在此代码中,值将打印在函数本身中(但它应该打印在主函数中)...

4

3 回答 3

1

将其更改为

import java.util.*;
public class inbetween {
public static void main (String[]args) {
    Scanner in = new Scanner (System.in);
    System.out.println("Enter range of values");
    int x =in.nextInt();
    int y =in.nextInt();
    int[] result = search(x,y);
    for (int i=0;i < result.length; i++)
      System.out.println(result[i]);
}

public static int[] search(int a, int b) {
      int length = (b-a)+1;
    int [] arr = new int [length];
    for(int i=0; i<length; i++)
    {
      a = a+1;
     int c;
     // int count=0;
      c = a%3;
      if (c==0) {
          arr[i] = a;
              }
    }
    return arr;
}
}
于 2013-09-10T13:45:18.337 回答
0

您需要将一个数组返回给 main:

package com.stackoverflow.homework;

import java.util.Arrays;
import java.util.Scanner;

public class Homework {

    public static void main(String[] args) {
        int[] result;
        Scanner in = new Scanner(System.in);

        System.out.println("Enter range of values: ");
        int x = in.nextInt();
        int y = in.nextInt();

        result = findNumbersBetween(x,y);

        for(int i=0; i<result.length; i++) {
            System.out.println(result[i]);
        }

    }

    private static int[] findNumbersBetween(int a, int b) {
        int[] temp = new int[(b-a)+1];
        int x = a;
        int i = 0;

        while(x <= b) {
            if(x % 3 == 0) {
                temp[i] = x;
                i++;
            }

            x++;
        }

        return Arrays.copyOfRange(temp, 0, i);
    }
}

还要记住,类名的第一个字母应始终大写!

于 2013-09-10T13:58:26.910 回答
0
  1. 在 main 中创建数组
  2. 将对数组的引用传递给函数以完成工作
  3. 在 main 中打印数组
于 2013-09-10T13:44:02.173 回答