我必须创建一个程序,要求用户输入一系列数字,并将输入保存在数组中。然后允许用户在数组中搜索数字并打印数组。我被困住了,因为它不允许我将输入存储在数组中。我还需要打印数组的帮助。
我正在上 Java 类(class),我们使用的教科书根本没有帮助,有人有关于好的 Java 教科书的推荐吗?
这是我到目前为止的代码:
import java.util.Scanner;
public class MyContainer {
private int [] values;
private int size;
public MyContainer() {
values = new int[50];
size=0;
}
public static void main(String [] args)
{
//load()
Scanner input = new Scanner(System.in);
double sum = 0;
System.out.print("Enter a positive number, negative number will end entry.");
double number = input.nextDouble();
int count = 0;
double average = 0;
int numofinput = 0;
while (number >= 0)
{
count++;
numofinput ++;
sum += number;
System.out.print("Enter a positive number, negative number will end entry.");
number = input.nextDouble();
}
sum = sum + number;
average = sum/numofinput;
System.out.print("The average of the numbers as of right now is "
+ average);
}
//search()
最佳答案
简单总结一下我所做的更改:
1) 你有 3 个变量做同样的事情,所以我去掉了其中 2 个。 (输入数量和计数)。
2) 您正在循环询问用户数字,但您从未将数字添加到数组中。
3) 我在循环中添加了一个条件,以便在 50 个数字后循环停止,这样就永远不会超过数组的大小。
4) 将大部分 main 移至另一个方法。 Java(和大多数其他语言)不允许静态方法访问非静态变量。因此 main 创建 MyContainer 的新实例,然后调用执行添加的方法。
5)我添加了一个打印列表方法,该方法仅使用循环遍历列表。
导入java.util.Scanner;
公共(public)类MyContainer{
private double[] values;
private int size;
public MyContainer() {
values = new double[50];
size = 0;
}
public void run(){
// load()
Scanner input = new Scanner(System.in);
double sum = 0;
System.out.print("Enter a positive number, negative number will end entry.");
double number = input.nextDouble();
//int 计数 = 0;//删除计数 双重平均 = 0;
while (number >= 0 && size < values.length) {
values[size] = number; //Line added
size++;
sum += number;
System.out.print("Enter a positive number, negative number will end entry.");
number = input.nextDouble();
}
sum = sum + number;
average = sum / size;
System.out.println("The average of the numbers as of right now is " + average);
}
public void printList(){
System.out.print("[");
for (int i = 0; i <= size; i++){
System.out.print(values[i]+", ");
}
System.out.println("end]");
}
public static void main(String[] args) {
MyContainer cont = new MyContainer();
cont.run();
cont.printList();
}
}
关于java - 存储在数组中并打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947786/