数组Java初学者

时间:2015-07-10 04:50:20

标签: java arrays

我无法将值存储到monthlySales数组中。另外,如何检索要在totalSales等其他方法中使用的值?另外,我在getSales()方法中有错误。

import java.util.Scanner;
import java.text.DecimalFormat;


public class SalesTracking 
{
    static DecimalFormat f = new DecimalFormat ("$#,##0.00");
    static Scanner input = new Scanner (System.in); //create a scanner object that reads from the keyboard (System.in)
    private static final double[] monthlySales = new double[12]; //create monthlysales array
    private static final String[] monthArray = {"January" , "February" , "March" , "April", "May",
              "June", "July", "August", "September", "October",
              "November", "December"}; //create 12-month array
    static void getSales(){
        int size = monthArray.length; 
        for (int i = 0; i < size; i++){
        System.out.print("Please Enter Sales for " + monthArray[i] + ":");
        monthlySales[i] = input.nextDouble();
        } //get sales method to store values into monthlysales
    }


    public static void main(String[] args){ 

        getSales();
        totalSales();
        computeHighestMonth(monthlySales);
        computeLowestMonth(monthlySales);

3 个答案:

答案 0 :(得分:3)

好吧,让我们分解你的多个子问题。

  

无法将值存储到我的monthlySales数组中。

首先,避免使用C语法并将声明写为:

private static final double[] monthlySales = new double[12];

这强调monthlySales属于类型 double[]。现在,为你的问题。下面这行是给你带来麻烦的。

monthlySales = input.nextDouble();

当您将monthlySales声明为final时,这实际上意味着您无法将引用变量指向其他任何内容。在这里,您尝试将变量指向double,这两者都不会发生,因为变量必须指向double[]final声明。

你想要这样,改变数组中的值是完全正常的(Java的final关键字有点奇怪):

monthlySales[i] = input.nextDouble();

  

另外,我在public static void getSales()方法上有错误。

这是因为您已在 getSales中定义了main()方法。在Java中,您无法在其他方法中定义方法(但是,您可以使用类来完成此操作)。

我相信您想要完全删除getSales定义,因为您的主要客户端似乎是从标准输入读取。如果需要从另一个类访问数组,请在main之外定义getter方法。

  

另外,我如何检索要在其他方法中使用的值,例如totalSales?

因为您已将值分配给静态成员monthlySalesmonthArray,所以您已经可以从其他静态方法访问这些变量。

请注意,由于您没有非静态变量或方法,因此无法有意义地创建多个SalesTracking实例,因为所有实例都将共享同一组数据。

  

void(无效类型)和getSales上的错误(参数getSales的非法修饰符;仅允许final)

这些来自getSales内的main定义。如果你在外面定义方法或完全删除它,你会没事的。

编辑:像这样修复您的getSales()

public static void getSales() {
    try (
        Scanner input = new Scanner(System.in); // try-with-resources
    ) {
        int size = monthArray.length; 
        for (int i = 0; i < size; i++){
            System.out.print("Please Enter Sales for " + monthArray[i] + ":");
            monthlySales[i] = input.nextDouble();
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

public static void main(String[] args) {
    getSales();
}

答案 1 :(得分:0)

就像在评论中已经说过的那样,将此方法移到主要之外。 然后,您需要在main中创建此类的实例,并通过构造函数或作为此类的参数传递import java.util.Scanner; public class SalesTracking { private static final double monthlySales[] = new double[12]; private static final String[] monthArray = {"January" , "February" , "March" , "April", "May", "June", "July", "August", "September", "October", "November", "December"}; static void totalSales(){ } static void averageSales(){ } static void highestMonth(){ } static void lowestMonth(){ } public static void getSalesUsingStaticMethodWhichBelongsToClass(double input) { SalesTracking salesTracking = new SalesTracking(); salesTracking.getSalesUsingNonStaticMethodWhichBelongsToInstanceAndRecommended(input); } public void getSalesUsingNonStaticMethodWhichBelongsToInstanceAndRecommended(double input) { int size = monthArray.length; for (int i = 0; i < size; i++){ System.out.print("Please Enter Sales for " + monthArray[i] + ":"); monthlySales[i] = input; } } public static void main(String[] args) { //create a scanner object that reads from the keyboard (System.in) Scanner input = new Scanner (System.in); getSalesUsingStaticMethodWhichBelongsToClass(input.nextDouble()); //OR Using Instance which you should be using . No need to make class method static for no reason SalesTracking salesTracking = new SalesTracking(); salesTracking.getSalesUsingNonStaticMethodWhichBelongsToInstanceAndRecommended(input.nextDouble()); }//end main }//end class

以下是您的代码的修改版本(我没有测试过,但应该可以使用)

def overlap(coors1, coors2, tolerance ):

    # Perform elementwise absolute subtractions between input arrays 
    sub_abs_vals = np.abs(coors1[None,:,:] - coors2[:,None,:])

    # Check for ANY equality along 0-th axis & ALL equality along 2-nd axis.
    # Return the corresponding row from first input array.
    return coors1[np.all(np.any(sub_abs_vals<=tolerance,axis=0),axis=1)]

在主类中不需要这样的长方法名称,但是可以推荐用于单元测试。我刚刚用它们来表明这一点

答案 2 :(得分:0)

*:请使用Java Jdk 1.8

实体:

class Sales {

public Month getMonth() {
    return month;
}

public void setMonth(Month month) {
    this.month = month;
}

private Month month;

public double getSales() {
    return sales;
}

public void setSales(double sales) {
    this.sales = sales;
}

private double sales;

@Override
public String toString() {
    return "month->" + getMonth() + ",sales->" + getSales();
}}

计算:

/**
  * @author puruidong
  * @version 2015-07-10
  */
public class Main {
private static final double monthlySales[] = new double[12];
private static final String[] monthArray = {"January", "February", "March", "April", "May",
        "June", "July", "August", "September", "October",
        "November", "December"};


private Set<Sales> salesList = new HashSet<Sales>(12);


public void totalSales() {

    double count = salesList.stream().mapToDouble(new ToDoubleFunction<Sales>() {
        @Override
        public double applyAsDouble(Sales value) {
            return value.getSales();
        }
    }).sum();
    System.out.println("total->" + count);
}

static void averageSales() {

}

static void highestMonth() {

}

static void lowestMonth() {

}

public void showSales() {
    salesList.forEach((x) -> {
        System.out.println(x.toString());
    });


}

public void getSalesUsingNonStaticMethodWhichBelongsToInstanceAndRecommended(Scanner sc) {
    int i = 0;
    while (i <= 11) {
        System.out.println("Please enter a month to be recorded?(1-12)");
        int months = sc.nextInt();
        Sales sales = new Sales();
        switch (Month.of(months)) {
            case JANUARY:
                sales.setMonth(Month.JANUARY);
                break;
            case FEBRUARY:
                sales.setMonth(Month.FEBRUARY);
                break;
            case MARCH:
                sales.setMonth(Month.MARCH);
                break;
            case APRIL:
                sales.setMonth(Month.APRIL);
                break;
            case MAY:
                sales.setMonth(Month.MAY);
                break;
            case JUNE:
                sales.setMonth(Month.JUNE);
                break;
            case JULY:
                sales.setMonth(Month.JUNE);
                break;
            case AUGUST:
                sales.setMonth(Month.AUGUST);
                break;
            case SEPTEMBER:
                sales.setMonth(Month.SEPTEMBER);
                break;
            case OCTOBER:
                sales.setMonth(Month.OCTOBER);
                break;
            case NOVEMBER:
                sales.setMonth(Month.NOVEMBER);
                break;
            case DECEMBER:
                sales.setMonth(Month.DECEMBER);
                break;
            default:
                System.err.println("--input error--");
                break;
        }
        if (sales.getMonth() != null) {
            sc.reset();
            System.out.println("Please enter turnover:");
            double turnover = sc.nextDouble();
            sales.setSales(turnover);
            salesList.add(sales);
        }
        i++;
    }
    showSales();
    System.out.println("----------------------------");
    totalSales();


}

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Main salesTracking = new Main();
    salesTracking.getSalesUsingNonStaticMethodWhichBelongsToInstanceAndRecommended(input);
}//end main

}//end class

结果:

Please enter a month to be recorded?(1-12)
1
Please enter turnover:
1
Please enter a month to be recorded?(1-12)
2
Please enter turnover:
2
Please enter a month to be recorded?(1-12)
3
Please enter turnover:
3
Please enter a month to be recorded?(1-12)
4
Please enter turnover:
4
Please enter a month to be recorded?(1-12)
5
Please enter turnover:
5
Please enter a month to be recorded?(1-12)
6
Please enter turnover:
6
Please enter a month to be recorded?(1-12)
7
Please enter turnover:
7
Please enter a month to be recorded?(1-12)
8
Please enter turnover:
8
Please enter a month to be recorded?(1-12)
9
Please enter turnover:
9
Please enter a month to be recorded?(1-12)
10
Please enter turnover:
10
Please enter a month to be recorded?(1-12)
11
Please enter turnover:
11
Please enter a month to be recorded?(1-12)
12
Please enter turnover:
12
------------------------------
month->DECEMBER,sales->12.0
month->JANUARY,sales->1.0
month->APRIL,sales->4.0
month->AUGUST,sales->8.0
month->MAY,sales->5.0
month->MARCH,sales->3.0
month->JUNE,sales->7.0
month->OCTOBER,sales->10.0
month->NOVEMBER,sales->11.0
month->FEBRUARY,sales->2.0
month->JUNE,sales->6.0
month->SEPTEMBER,sales->9.0
----------------------------
total->78.0