我在Java中有一个简单的项目。
该项目是一个针对想要输入其学生成绩(每个学生三个成绩)的老师的程序,该老师具有五个私有属性name
,grade1
,grade2
,{{1} },grade3
和三种方法:average
,readGrades()
)和GetAverage(
。除了我所有的问题外,我还是所有人,但我的问题是,无论我做什么,输出总是给我输入的最新学生的平均值而不是最高分数。我也应该打印出他的名字而不是平均值。
有人告诉我使用ArrayList,但老实说我不知道怎么做?
因此,如果有人可以帮助我,我将不胜感激。
这是我到目前为止所拥有的
getName()
答案 0 :(得分:0)
您的代码中的几个问题如下:
1)之所以为您提供最新学生的输出,是因为您一直在修改单个对象,因为输入更多成绩和姓名的逻辑一直在学生本身之内,因此应该淘汰。
2)要获取名称而不是平均值,请在打印时致电getName。
3)要处理多个学生,您可以采用do you wish to continue
方法询问main
的逻辑,并使用ArrayList
方法使main
个学生处理多个学生对象,或者您也可以将其与其他收藏集一起使用
List<Student> students = new ArrayList<>();
从此处循环,并使用students.add(studentObj)
将学生对象添加到列表中。
然后使用getAverage来获得最高的学生对象平均值,并从列表中找到平均值最高的学生并打印出来。
那样就可以了。尝试其中的一些,如果您遇到困难,请告诉我们。
答案 1 :(得分:0)
该类只有一个实例对象,因此,当您读取更多学生的数据时,下一个学生将替换前一个学生的数据。
在这种情况下,要保存所有学生并获取有关所有学生的信息,最好使用ArrayList,然后将所有新数据推送到该列表中。 例如:
List<Student> students = new ArrayList<>();
最后,您可以获得所需的平均值。
编辑:
使用ArrayList的代码:
学生班
public class Student {
private String name;
private int grade1, grade2, grade3;
private double average;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade1() {
return grade1;
}
public void setGrade1(int grade1) {
this.grade1 = grade1;
}
public int getGrade2() {
return grade2;
}
public void setGrade2(int grade2) {
this.grade2 = grade2;
}
public int getGrade3() {
return grade3;
}
public void setGrade3(int grade3) {
this.grade3 = grade3;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public double calculateAverage() {
return (grade1 + grade2 + grade3) / 3;
}
}
主班
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class MainStudent {
public static void main(String[] args) {
//Create a list of student
List<Student> studentList = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int g1, g2, g3;
String name;
int choice;
do {
//Instantite a new object student
Student student = new Student();
System.out.println(" --Please enter the student name: ");
name = input.next();
student.setName(name);
System.out.println(" --Please enter the first grade: ");
g1 = input.nextInt();
student.setGrade1(g1);
System.out.println(" --Please enter the the second grade: ");
g2 = input.nextInt();
student.setGrade2(g2);
System.out.println(" --Please enter the the third grade: ");
g3 = input.nextInt();
student.setGrade3(g3);
System.out.println(" Do you want to continue? enter the number ");
System.out.println(" 1- YES 2- NO ");
choice = input.nextInt();
student.setAverage(student.calculateAverage());
//Push a new object to student list
studentList.add(student);
}
while (choice != 2);
//Get student object with the higher average
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
System.out.println("THE HIGHEST AVG :" + higherStudent.getAverage() + "\n BELONG'S TO: " + higherStudent.getName());
}
}
我已经将while代码转移到main方法上,并创建了一个新的方法来计算平均值,因为getAverage是我们将如何获取计算值的方法。
编辑:通过简单循环
获得更高的平均值替换:
Student higherStudent = Collections.max(studentList, Comparator.comparing(c -> c.getAverage()));
通过:
Student higherStudent = new Student();
for(int i = 0; i < studentList.size(); i++) {
if(i == 0) {
higherStudent = studentList.get(i);
} else if(higherStudent.getAverage() < studentList.get(i).getAverage()) {
higherStudent = studentList.get(i);
}
}
答案 2 :(得分:0)
我认为您的问题是您需要创建多个学生对象实例以存储多个学生的数据。您在代码中所做的就是始终将数据替换为最后一个输入。这是您可以做什么的示例。
Student student1 = new Student();
Student student2 = new Student();
Student student3 = new Student();
您还将需要一个数据结构来存储学生对象的所有实例,您可以使用Array或ArrayList。然后,您将学生对象的每个实例添加到数据结构中。之后,您可以比较阵列中所有学生的平均值。
答案 3 :(得分:0)
首先,从数据持有者.spec
类中删除用户交互方法<?php
require("../includes/config.php");
//select a particular admin by id
$admin_id = isset($_GET["admin_id"]) ? $_GET["admin_id"] : '';
$stmt = $pdo->prepare("SELECT * FROM admin WHERE admin_id=:admin_id");
$stmt->execute(['admin_id' => $admin_id]);
$admin = $stmt->fetch(); # get admin data
if (!$admin)
{
header("Location: login.php");
}
//Class import for image uploading
//classes is the map where the class file is stored (one above the root)
include ("../classes/upload/upload_class.php");
//select a particular course by id
$course_id = isset($_GET["course_id"]) ? $_GET["course_id"] : '';
$stmt = $pdo->prepare("SELECT * FROM courses WHERE course_id=:course_id");
$stmt->execute(['course_id' => $course_id]);
$course = $stmt->fetch(); # get course data
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// validate submission
if (empty($_POST["coursename"]))
{
echo "Provide the course name.";
}
if (empty($_POST["courseduration"]))
{
echo "Provide the course duration.";
}
if (empty($_POST["coursecode"]))
{
echo "Provide the course code.";
}
if (empty($_POST["fees"]))
{
echo "Enter total fees for the course.";
}
// validate coursename
//$coursename = ($_POST["coursename"]);
//if (!preg_match("/^[a-zA-Z0-9]*$/", $coursename))
// {
// echo "A course name must contain only letters and numbers.";
// }
if (strlen($_POST["coursename"]) < 20 || strlen($_POST["coursename"]) > 50)
{
echo "A course name must be from 20 to 50 characters.";
}
// validate course duration
//$courseduration = ($_POST["courseduration"]);
//if (!preg_match("/^[a-zA-Z0-9]*$/", $courseduration))
//{
// echo "Invalid course duration.";
//}
// validate coursecode
//$coursecode = ($_POST["coursecode"]);
//if (!preg_match("/^[a-zA-Z0-9]*$/", $coursecode))
//{
// echo "A course ID can only contain letters and numbers.";
//}
if (strlen($_POST["coursecode"]) < 3 || strlen($_POST["coursecode"]) > 10)
{
echo "A course code must be from 3 to 10 characters.";
}
if ($_POST["coursecode"] === false)
{
echo "The course code has already been taken.";
}
//This is the directory where images will be saved
$max_size = 1024*250; // the max. size for uploading
$my_upload = new file_upload;
$my_upload->upload_dir = "../images/courses/";
$my_upload->extensions = array(".png", ".gif", ".jpeg", ".jpg");
// $my_upload->extensions = "de";
$my_upload->max_length_filename = 50;
$my_upload->rename_file = true;
$my_upload->the_temp_file = $_FILES['courseimage']['tmp_name'];
$my_upload->the_file = $_FILES['courseimage']['name'];
$my_upload->http_error = $_FILES['courseimage']['error'];
$my_upload->replace = "y";
$my_upload->do_filename_check = "n";
if ($my_upload->upload())
{
$full_path = $my_upload->upload_dir.$my_upload->file_copy;
$imagename = $my_upload->file_copy;
}
else
{
$imagename = "";
}
if (!empty($_POST["coursename"]))
{
$data = [
'coursename' => $coursename,
'course_title' => $course_title,
'meta_keywords' => $meta_keywords,
'meta_description' => $meta_description,
'short_desc' => $short_desc,
'coursedesc' => $coursedesc,
'courseduration' => $courseduration,
'coursecode' => $coursecode,
'fees' => $fees,
'courseimage' => $my_upload->file_copy,
];
$result = "UPDATE courses SET coursename=:coursename, course_title=:course_title, meta_keywords=:meta_keywords, meta_description=:meta_description, short_desc=:short_desc, coursedesc=:coursedesc, courseduration=:courseduration, coursecode=:coursecode, fees=:fees', courseimage=:courseimage WHERE course_id=:course_id";
$stmt= $dpo->prepare($result);
$stmt->execute($data);
// if username is in database
if ($stmt === false)
{
echo "There was an error modifying this course.";
}
// redirect to list courses page
header("Location: list-courses.php");
}
}
// render the header
include("templates/header.php");
// render modify course template
include("templates/modify-course_template.php");
// render the footer
include("templates/footer.php");
?>
。应该在外面。我认为您不应该将<?php
$course_id = isset($_GET["course_id"]) ? $_GET["course_id"] : '';
$stmt = $pdo->prepare("SELECT * FROM courses WHERE course_id=:course_id");
$stmt->execute(['course_id' => $course_id]);
$rows = $stmt->fetch();
echo "$rows[0]['coursename']";
echo "$rows[0]['course_title']";
?>
作为单独的字段。每次调用readGrades()
方法时,这都不是一个大数字来计算它:
Student
其次,请创建单独的方法,该方法与用户(或其他来源)进行交互,以检索所需的学生人数。
average
最后是非常简单的客户代码:
getAverage()
答案 4 :(得分:0)
我正在提供一种不使用List/ArrayList
的替代方法。由于这是家庭作业,因此我不会提供代码。
由于要求查找的是平均水平最高的学生,并且您一次要收集每个学生和三个年级,因此您只需一次跟踪两个Student实例。得分最高的bestStudent
,一个正在输入currentStudent
。
输入每个学生后,检查currentStudent
的平均值是否高于bestStudent
的平均值。如果是的话,她就是你的新老师的宠物。否则,丢弃。请记住,您需要以不同的方式处理第一个学生。