在Java中为数组索引分配不同的数字

时间:2016-02-04 13:39:38

标签: java arrays indexing

我正在尝试为数组的索引分配不同的数字而不修改数组。例如,在我的代码中它打印Salesperson 0,Salesperson 1等,因为它在我的代码中获取数组的索引ID。我想要实现的是销售员1的信息被分配到我的阵列上的索引0,以便它不会在我的输出上显示为销售员0。

这是我的代码。

import java.util.Scanner;
import java.text.NumberFormat;

public class Sales {

public static void main(String[]args)
    {
        NumberFormat money = NumberFormat.getCurrencyInstance();
        //part where program asks how many persons to compute
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number of Salesperson: ");
        int SALESPEOPLE = scan.nextInt();

        //part where variables are declared
        int[] sales = new int[SALESPEOPLE];
        int sum;
        float ave;
        int max_sales=0;
        int max_person=0;
        int min_sales=0;
        int min_person=0;


            //part where values for sales are asked and  entered
        for (int i=0; i<sales.length; i++)
            {
                System.out.print("Enter sales for salesperson "+i+": ");
                sales[i]=scan.nextInt();

            //part where sales are compared to find the minimum and maximum sales
                if (i == 0)
                    {
                        min_sales = sales[i];
                        max_sales = sales[i];
                    }
                if (sales[i] > max_sales)
                    {
                        max_sales = sales[i];
                        max_person = i;
                    }
                if (sales[i] < min_sales)
                    {
                        min_sales=sales[i];
                        min_person=i;
                    }
            }

        System.out.println("\nSalesperson           Sales");
        System.out.println("-----------         --------");
        sum=0;
        ave=0;

            //part where the sales are displayed
        for (int i=0; i<sales.length; i++)
            {
                System.out.println("    "+i+"                "+money.format(sales[i]));
                sum += sales[i];
                ave = sum/SALESPEOPLE;
            }
        System.out.println("\nTotal sales "+money.format(sum));
        System.out.println("Average sales "+money.format(ave));
        System.out.println("Salesperson "+min_person+" had the highest sale with "+money.format(min_sales));
        System.out.println("Salesperson "+max_person+" had the highest sale with "+money.format(max_sales));
    }


}

3 个答案:

答案 0 :(得分:0)

您无法更改数组的索引。但是如果你想以一种在你访问阵列的1索引时打印salesperson0的方式来改变输出,你就可以做到托马斯所说的。

答案 1 :(得分:0)

如果我理解正确,只需更改您要打印的内容

System.out.print("Enter sales for salesperson "+(i+1)+": ");

此外,这一行

System.out.println("    "+(i+1)+"                "+money.format(sales[i]));

此外,您还会在结尾处复制输出中的最高销售字符串

除此之外,我发现您的代码没有任何问题

答案 2 :(得分:-2)

  • 将数组值保存在另一个数组中,交换它们
  • 为索引定义规则...也许您可以为数组创建一个函数,如果您提供索引y,它将在索引x处返回值....