我尝试过以下代码:
*ngIf
如果我的困惑到处都是,我很抱歉。但总之,我遇到了麻烦:
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter weight 1: " + reader.nextDouble());
double weightOne = reader.nextDouble();
System.out.println("Enter weight 2: " + reader.nextDouble());
double weightTwo = reader.nextDouble();
System.out.println("Enter weight 3: " + reader.nextDouble());
double weightThree = reader.nextDouble();
System.out.println("Enter weight 4: " + reader.nextDouble());
double weightFour = reader.nextDouble();
System.out.println("Enter weight 5: " + reader.nextDouble());
double weightFive = reader.nextDouble(); /* Type your code here. */
return;
}
}
答案 0 :(得分:0)
首先创建一个数组:
// create array of doubles including 5 fields
double[] MyArray = new double[5];
并使用for循环迭代它并在其中存储值:
for(int x = 0; x < MyArray.length; x = x + 1)
{
System.out.println("Enter value: ");
MyArray[x] = reader.nextDouble();
}
答案 1 :(得分:0)
我知道这有点晚了,但是我正在zyBooks实验室进行同样的活动。我注意到上面的代码仅差一点。活动的一部分是使输出看起来像
Enter weight 1: 236
Enter weight 2: 89.5
Enter weight 3: 142
Enter weight 4: 166.3
Enter weight 5: 93
上面的代码将只显示为
Enter weight: 236
Enter weight: 89.5
Enter weight: 142
Enter weight: 166.3
Enter weight: 93
要解决此问题,只需将索引添加到打印语句中就可以对输出进行一些调整
for (i = 0; i < MyArray.length; i = ++i) {
System.out.println("Enter value " + (i + 1) + ": ");
MyArray[i] = reader.nextDouble();
}
您需要将1加到索引,否则您将从0开始到4结束。我在下面提供了我的代码,供那些需要对此分配额外帮助的人使用。它确实通过了所有6张支票,但100%可能不是最有效。
import java.util.Scanner;
public class PeopleWeights {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i;
int x;
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.println("Enter weight " + (i + 1) + ": ");
userVals[i] = scnr.nextDouble();
}
System.out.println("");
System.out.print("You entered: ");
for (i = 0; i < NUM_ELEMENTS; ++i) {
System.out.print(userVals[i] + " ");
}
System.out.println("");
double totalWeight = 0.0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
totalWeight += userVals[i];
}
System.out.println("Total weight: " + totalWeight);
double averageWeight = 0.0;
averageWeight = totalWeight / NUM_ELEMENTS;
System.out.println("Average weight: " + averageWeight);
double maxWeight = userVals[0];
for (i =0; i < NUM_ELEMENTS; ++i) {
if (userVals[i] > maxWeight) {
maxWeight = userVals[i];
}
}
System.out.println("Max weight: " + maxWeight);
return;
}
}