gpt4 book ai didi

java - 将元素输入数组

转载 作者:行者123 更新时间:2023-11-30 10:04:17 28 4
gpt4 key购买 nike

我正在尝试将元素输入到具有未知元素值或未知数量元素的数组中

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();
}

预期的结果应该是所有输入数字的总和,但我的结果是它们的总和然后加倍。

最佳答案

在您的第二个“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);

关于java - 将元素输入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953315/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com