我正在寻找一个Java程序,该程序使用数组,for
循环和一种方法来对4个人进行3个问题的调查。每个问题都会有一个是或否的答案。调查的总体结果应采用百分比格式。
I
First first first:按照惯例,Java类始终使用大写字母。因此,将survey
重命名为Survey
。
第二,将所有变量/常量移到代码顶部。它使阅读更容易。例如,person
应该在main
方法的第一行中声明,甚至在类中声明为常量。
Thirdly,请勿将变量用于应导出的值。例如,您声明了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];