数组中的零值

时间:2013-03-11 21:06:20

标签: java

将函数放入类后,我的数组得到零(0)结果。这是为什么? 没有什么改变我只是复制粘贴在课堂上?我还应该在课堂上投入其他任何工作吗?

import java.util.*;//import library

class Input
{

    public Input (int size,int startV,int endingV)
      {

         //declarations of variables
        double difference;
        double[] array= new double[size];

        array[0]=startV;

     //calculating the difference to add on each number in the array
     difference=(endingV-startV)/size;

    for (int counter=1;counter<size;counter++) //for loop to fill the array
              {
        array[counter]=array[counter-1] + difference;           
          }


      }

    public Input enter(int size,int startV,int endingV)
      {

        //declarations of variables
        double difference;
        double[] array= new double[size];

        array[0]=startV;

             //calculating the difference to add on each number in the array
        difference=(endingV-startV)/size; 

            for (int counter=1;counter<size;counter++) //for loop to fill the array
        {
            array[counter]=array[counter-1] + difference;           
        }

            return this;
    }
}

class Show
{
    public Show (int size,double[] array)
    {

        for (int i=0;i<size;i++) //for loop to print the array
            System.out.println("This is the array " + i+ ": " + array[i]);

    }

    public Show print(int size,double[] array)
    {

        for (int i=0;i<size;i++) //for loop to print the array
        System.out.println("This is the array " + i+ ": " + array[i]);

        return this;
    }
}

public class Assignment2 
{

    public static void  main(String[] args)
    {
        //declaring variables
        int startV,endingV;
        int size=0;



        System.out.print("Give the size of the array:");//Print message on screen
        size = new Scanner(System.in).nextInt();//asking for the size of array

            double[] array= new double[size]; //creation of array

    System.out.print("Give the starting value of the array:");
    startV = new Scanner(System.in).nextInt();//asking for the starting value of array

    System.out.print("Give the ending value of the array:");
    endingV = new Scanner(System.in).nextInt();//asking for the last value of array

    //calling the functions from the other classes 

        Input enter= new Input(size,startV,endingV);
        Show print= new Show(size,array);

    }



}

2 个答案:

答案 0 :(得分:1)

以下可能不是您想要的:

difference=(endingV-startV)/size;

由于startVendingVsize都是整数,因此使用整数(截断)除法。

此外,每次需要读取值时,请创建并使用单个Scanner,而不是创建新的。{/ p>

答案 1 :(得分:0)

//calling the functions from the other classes

不,你没有。你只需创建实例。