使用用户输入执行计算并存储到arrray中

时间:2016-01-26 19:46:53

标签: java arrays for-loop input

我正在尝试使用用户输入的内容作为数组的起点,然后它将对其进行平方并添加一个并继续直到存储25个元素。我知道这可以通过for循环来完成,我只是不确定如何让数组以用户输入开始。

import java.util.*;

public class arrayList {

    static Scanner console = new Scanner(System.in);

    public static void printArrayDouble(double[] list, int numOfElements) {
        for ( int index = 0; index < numOfElements; index++)
            System.out.print(list[index] + " ");
    }

    public static void main(String [] args) {


        double sqNum;
        double num;
        double [] sqNums = new double[25];
        double index = 0;   

        System.out.println("Please enter any integer!!");

        num = console.nextInt();
        sqNum = num;
        index = num;


        for(double i = 0; i < sqNums.length; i++) { 
            sqNums[(int) i] = Math.pow(i, 2);
        }

        arrayList.printArrayDouble(sqNums, sqNums.length);

    }

    }

我正在尝试使用用户输入,因此列表的第一个数字(比如2)将被平方,然后列表的下一个数字将是3然后是4然后是5,依此类推到第25个元素,每个他们被平方。如果输入为n,则下一个元素将为n + 1,然后变为n,依此类推。

2 个答案:

答案 0 :(得分:0)

根据我的理解,对于输入2,您希望输出为

4 9 25 .... 25th element

如果是,则以下代码将执行此操作

import java.util.*;

public class arrayList {

    static Scanner console = new Scanner(System.in);

    public static void printArrayDouble(double[] list) {
        for ( int index = 0; index < list.length; index++)
            System.out.print(list[index] + " ");
    }

    public static void main(String [] args) {


        double[] sqNums = new double[25];

        System.out.println("Please enter any integer!!");

        num = console.nextInt();


        for(int i = 0; i < 25; i++) { 
            sqNums[i] = Math.pow(i+num, 2);
        }

        arrayList.printArrayDouble(sqNums);

    }

}

答案 1 :(得分:0)

    public class arrayList
{

    static Scanner console = new Scanner(System.in);

    public static void printArrayDouble(double[] list, int numOfElements)
    {
        for (int index = 0; index < numOfElements; index++)
            System.out.print(list[index] + " ");
    }

    public static void main(String[] args)
    {

        double sqNum;
        double num;
        double[] sqNums = new double[25];
        double index = 0;

        System.out.println("Please enter any integer!!");

        num = console.nextInt();
        sqNum = num;
        index = num;

        for (double i = 0; i < sqNums.length; i++)
        {
            sqNums[(int) i] = Math.pow(num, 2);
            num++;
        }

        arrayList.printArrayDouble(sqNums, sqNums.length);

    }

}