【发布时间】:2023-03-20 22:02:01
【问题描述】:
我希望创建一个 Java 程序,该程序使用数组、for 循环和对 4 个人进行 3 个问题的调查的方法。每个问题都有一个是或否的答案。调查的总体结果应采用百分比格式。
我
【问题讨论】:
-
另外,“计算不正确”是什么意思?你得到什么输出?你期望得到什么?
我希望创建一个 Java 程序,该程序使用数组、for 循环和对 4 个人进行 3 个问题的调查的方法。每个问题都有一个是或否的答案。调查的总体结果应采用百分比格式。
我
【问题讨论】:
首要任务:按照惯例,Java 类总是有一个大写字母。所以将survey 重命名为Survey。
其次,将所有变量/常量移至代码顶部。它使阅读更容易。例如,person 应该在您的 main 方法的第一行声明,或者甚至在您的类中声明为常量。
第三,不要将变量用于应该派生的值。例如,您声明int NumberQuestions = 3;,但实际上这是问题数组的长度。所以改用长度。您确实使用它来初始化数组,因此请改用另一种初始化数组的方式,例如:
// Number of Questions
String[] question = new String[] {
"Have you ever like shopping online? ",
"Did you start your christmas shopping? ",
"Are you waiting for Black Friday sales? "};
这可能是个人喜好问题,但我更喜欢使用while...do 而不是do...while。
另一个重要警告:请记住,数组索引在 Java 中从零 (0) 开始,而不是 1。然而,您开始将用户 #1 的响应保存在第 1 行中,从而将第 0 行留空。
但是,当您进行数学运算(平均...)时,您会返回第一行,因此您没有得到您期望的结果。我想知道您为什么要创建一个 person + 1 的数组,但这可能是因为您试图避免使用 ArrayIndexOutOfBoundsException。
您还可以简化此if/then/else 语句:
if (userInput.equalsIgnoreCase("yes")) {
answer[personIndex][questionIndex] = 1;
} else {
answer[personIndex][questionIndex] = 0;
}
可以简单写成:
answer[personIndex][questionIndex] = userInput.equalsIgnoreCase("yes") ? 1 : 0;
package eu.webfarmr;
import java.util.Scanner;
public class Survey {
// Number of people
private final static int PERSON_COUNT = 4;
// Questions
private final static String[] QUESTIONS = new String[] {
"Have you ever like shopping online? ",
"Did you start your christmas shopping? ",
"Are you waiting for Black Friday sales? " };
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter Yes or No:");
// people Loop
int[][] answer = new int[PERSON_COUNT][QUESTIONS.length];
for (int personIndex = 0; personIndex < PERSON_COUNT; personIndex++) {
System.out.println("person " + personIndex);
// Question Loop
for (int questionIndex = 0; questionIndex < QUESTIONS.length; questionIndex++) {
// Answer yes or no only
boolean valid = false;
do {
System.out.print(QUESTIONS[questionIndex]);
String userInput = in.next();
valid = userInput.equalsIgnoreCase("yes") || userInput.equalsIgnoreCase("no");
if (!valid) {
System.out.println("Please enter Yes or No");
} else {
answer[personIndex][questionIndex] = userInput.equalsIgnoreCase("yes")? 1:0;
}
} while (!valid);
}
System.out.println();
}
// survey results
System.out.println("Survey Results\t\t\t\t Yes\t No");
for (int i = 0; i < QUESTIONS.length; i++) {
int total = 0;
for (int j = 0; j < PERSON_COUNT; j++)
total += answer[j][i];
int percent = (total * 100) / PERSON_COUNT;
System.out.println(QUESTIONS[i] + "\t " + percent + "%\t " + (100 - percent) + "%");
}
}
}
【讨论】:
你有一个 5 行 4 列的矩阵,这是主要问题。
将第一个循环改为:
for(int i = 0; i < person; i++)
以及矩阵的创建:
int[][] answer = new int[person][NumberQuestions];
【讨论】: