我正在進行作業和編輯程序。我要求用戶輸入他們的銷售人員編號,產品編號和銷售量。我試圖將銷售數據保存爲一個名爲sales
的數組。但是,我無法正確訪問二維數組的元素。將用戶輸入保存到數組中並確保它不違反索引
數組定義爲:
double[][] sales = new double[ 5 ][ 4 ]
但是當我嘗試這樣做:
sales[ product - 1 ][ person - 1 ] += amount;
...它不保存增加銷售額。我認爲我違反了陣列的索引。
這裏是整個代碼塊:
import java.util.Scanner;
public class Sales2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// sales array holds data on number of each product sold
// by each salesperson
double[][] sales = new double[ 5 ][ 4 ]; // 5 salespeople,
//4 products each person
System.out.print("Enter salesperson number (-1 to end): ");
int person = input.nextInt(); // the salesperson index
while (person != -1)
{
System.out.print("Enter product number: ");
int product = input.nextInt(); // the product index
// prompt user to enter product number and save it as an integer
System.out.print("Enter sales amount: ");
double sales = input.nextInt();
// promp to enter sales amont and save it as double
sales[ product - 1 ][ person - 1 ] += amount;
// Having trouble with the following. I tried to manipulate
// the above array but nothing will work. thanks
// error-check the input number for the array boundary
// that is the person index should be 0 - 3
// and the product index should be 0 - 4
// notice that array index start with 0
// save the input to the sales
//array like sales[ product - 1 ][ person - 1 ] += amount;
// or print message for the out of boundary input
System.out.print("Enter salesperson number (-1 to end): ");
person = input.nextInt(); // input for next sales person
} // end while
// total for each salesperson
double[] salesPersonTotal = new double[ 4 ];
// display the table
for (int column = 0; column < 4; column++)
salesPersonTotal[ column ] = 0; // Initialize the array
System.out.printf("%8s%14s%14s%14s%14s%10s\n",
"Product", "Salesperson 1", "Salesperson 2",
"Salesperson 3", "Salesperson 4", "Total");
// To do -
// for each column of each row, print the appropriate
// value representing a person's sales of a product
// and calculate and print out the total for each product
System.out.printf("%25s","1", "2", "3",
"4", "5");
// To do -
// print out for each sales person total
// I have been messing with these numbers but
//it doesnt seem to be working.
} // end main
} // end class Sales2
您可能想將其作爲一個實際問題。 – weltraumpirat
@weltraumpirat你是什麼意思? –
你從來沒有問過。只是發佈你的任務,並等待別人解決它不會對你或任何其他人有任何好處。如果您在理解數組時遇到問題,那麼詢問如何訪問二維數組中的值,或者如果您想對用戶輸入進行值檢查,請提問 - 無論哪種方式,使這個實際問題將幫助其他人解決您的問題具體問題,並且它還將使其他用戶能夠找到他們自己問題的答案,如果它是相關的。 – weltraumpirat