我试图将所有元素添加到一个通过用户输入决定的数组中,每次运行我在下面构建的代码时,我都会得到一个显然不是元素之和的数字。我做错了什么?
import java.util.Scanner;
public class SumProduct
{
public static void main (String []args)
{
Scanner input = new Scanner (System.in);
int[] array1 = new int [input.nextInt()];
input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
for (int i = 0; i < array1.length; i++)
{
int j = array1[i];
int k = array1[i]+1;
int sum = j + k;
System.out.print(sum);
}
}
}
最佳答案
如果您要这样做,您可能希望提示用户输入数组的大小。这行代码允许用户输入的任何内容都是数组的大小。
int[] array1 = new int [input.nextInt()]; //this sets the size of the array through user input
当前上下文中不存在扫描:
input = scan.nextInt(); // this is invalid syntax as scan is not the Scanner you created
for (int i = 0; i < array1.length; i++)
{
array1[i] = input.nextInt();
}
我这样做是为了不断向数组添加元素:
// no need for this: input = scan.nextInt();
for (int i = 0; i < array1.length; i++)
{
System.out.println("Enter integer to add:");
array1[i] = input.nextInt();
}
如果您一次只向 sum 变量添加一个元素而不是两个元素,则此代码将为您提供元素的总和:
int sum = 0;
for (int i = 0; i < array1.length; i++)
{
sum += array1[i];
System.out.print(sum); // this will print out sum after each addition
}
System.out.print(sum); // this will print out sum after the entire array is summed
添加一些逻辑以仅允许用户向数组输入这么多数字也会很有帮助。您将需要在某个时刻继续将数据输入到数组中。然后,当您完成从用户那里获取数据时,还记得关闭扫描仪:
input.close();
关于java - 添加通过用户输入决定的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059276/