Java 数组中的零值
将函数放入类后,数组中的结果为零。为什么呢? 没什么变化我只是复制粘贴在课堂上?我还应该在课堂上放些什么来让它发挥作用吗Java 数组中的零值,java,Java,将函数放入类后,数组中的结果为零。为什么呢? 没什么变化我只是复制粘贴在课堂上?我还应该在课堂上放些什么来让它发挥作用吗 import java.util.*;//import library class Input { public Input (int size,int startV,int endingV) { //declarations of variables double difference; doubl
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);
}
}
以下可能不是您想要的:
difference=(endingV-startV)/size;
由于startV、endingV和size都是整数,因此使用整数截断除法
另外,创建并使用一个扫描程序,而不是每次需要读取值时都创建一个新的扫描程序。//从其他类调用函数
不,你没有。您只需创建实例。我仍然不明白为什么数组中的值为0。我的意思是,这可能会改变结果,但不能解释为什么我会得到0。如果我刚刚粘贴的不是证明我在做作业,那么我不知道该说什么m8我现在问的问题与我以前问的问题不同。这只是一个代码的转载,可以问一个不同的问题,因为我的另一篇关于同一代码的帖子是根据我之前问的问题的需要编辑的。因为我在问一个新问题,有人建议我在一个新的岗位上这样做,以造福社区。如果你对我的问题没有答案,我会恳请你停止在我的帖子上发垃圾邮件。那是以前的评论,没有改变它。对不起:这不会改变现状。调用新输入时,不会用值填充数组。输入构造函数对数组一无所知。它创建自己的数组。