我正在尝试将元素值未知或元素数量未知的元素输入数组
public class Sales
{
public void salesAmount()
{
Scanner scan = new Scanner(System.in);
int sum = 0;
int salespeople = 0;
//Create printstatement to ask the user to ("enter the number of sales people");
System.out.println("Enter the number of sales people: ");
//store the response in salespeople
salespeople = scan.nextInt();
//Create an int array called sales that will have the number entered by user as the number of elements
int[] sales = new int[salespeople];
//create a for loop that will loop through the array sales.
for(int i = 0; i < salespeople; i++)
{
//Create print statement that says: ("Enter sales for salesperson " + i + ": ");
System.out.println("Enter sales for salesperson " + i + ": ");
sales[i] = scan.nextInt();
//store response in sales[i]
sum = sum + sales[i];
}
System.out.println("Salesperson\tSales");
System.out.println("--------------------");
for (int i=0; i<sales.length; i++)
{
System.out.println(i + "\t" + sales[i]);
sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
}
}
我将所有内容打印在第二个文件中,这是下面的代码:
public static void main(String[]args)
{
Sales sales = new Sales();
sales.salesAmount();
}
预期结果应该是所有输入数字的总和,但是我的结果是它们的总和,然后加倍。
答案 0 :(得分:1)
在第二个“ for循环”中,删除总和。您会在2个循环中进行两次加法操作
for (int i=0; i<sales.length; i++)
{
System.out.println(i + "\t" + sales[i]);
//sum += sales[i];
}
System.out.println("\nTotal sales: " + sum);
答案 1 :(得分:0)
问题是您将总和加倍两次,一次遍历销售人员:
sum = sum + sales[i];
然后再打印总销售额:
for (int i=0; i<sales.length; i++)
{
System.out.println(i + "\t" + sales[i]);
sum += sales[i];
}
因此,您需要在第二个循环之前重设总和-即sum = 0;
,或者从第二个循环中删除行sum += sales[i];
。