gpt4 book ai didi

java - 向我解释一下这些构造函数在这个程序中做了什么?

转载 作者:行者123 更新时间:2023-12-01 13:45:42 25 4
gpt4 key购买 nike

我刚刚了解了构造函数,并且必须在最近的程序中使用它们。我猜对了,但我仍然不明白他们到底在做什么。如果有人可以使用这个程序作为引用给我一个详细的解释,那就太好了!

主类

public class Student 
{

public static void main(String[]args)
{

String question, name, GPAStr, studentNumberStr;
int studentNumber;
double GPA;

question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");

while (question.equalsIgnoreCase("Y"))
{
name = JOptionPane.showInputDialog("Please enter your name.");

studentNumberStr = JOptionPane.showInputDialog("Please enter your student number.");
studentNumber = Integer.parseInt(studentNumberStr);

GPAStr = JOptionPane.showInputDialog("Please enter your GPA.");
GPA = Double.parseDouble(GPAStr);

StudentIO students = new StudentIO(name, GPA);

// ouput

JOptionPane.showMessageDialog(null, students.getDeansList());

question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");

if (question.equalsIgnoreCase("N"))
//display the content of players processed

{
JOptionPane.showMessageDialog(null,StudentIO.getCount());
}
}
}
}

第二类(带有标签的构造函数)

public class StudentIO 
{

//instance fields

private String name;
private double GPA;

// static fields

private static final double GPAMIN=3.0;
private static int count = 0;

public StudentIO(String theName, double theGPA) // constructor
{
name = theName;
GPA= theGPA;

count = count +1;
}

public StudentIO() //no arg constructor
{
name = " ";
GPA = 0;

count = count +1;
}

public void setName(String theName)
{
name = theName;
}

public void setGPA(double theGPA)
{
GPA = theGPA;
}


public String getName()
{
return name;
}

public double getGPA()
{
return GPA;
}

public String getDeansList()
{
if(GPA >= GPAMIN)
return (name + ", has made the Dean's List!");
else
return(name + ", did not make the Dean's List!");

}

public static String getCount()
{
return ("You processed " + count + "students.");
}
}

最佳答案

StudentIO students = new StudentIO(name, GPA);

将创建一个名为 Students 的 StudentIO 对象,并将名称和 GPA 参数影响到使用第一个承包商创建的对象:

 public StudentIO(String theName, double theGPA)  // constructor
{
name = theName;
GPA= theGPA;

count = count +1;
}

这相当于调用:

StudentIO students = new StudentIO();
students.setName(name);
students.setGPA(GPA);

将使用第二承包商:

public StudentIO()    //no arg constructor
{
name = " ";
GPA = 0;

count = count +1;
}

有两种方法

public void setName(String theName)
{
name = theName;
}

public void setGPA(double theGPA)
{
GPA = theGPA;
}

最后,这两种方法给你相同的结果,这是一种风格问题,有时我们被迫在强耦合对象中使用秒一个。

关于java - 向我解释一下这些构造函数在这个程序中做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20390199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com