我正在编写一个由2个类组成的程序。我的第一堂课从用户那里收集数据并将其存储在变量中。
public class UserData
{
public static void main (String [] args)
{
int grade;
String nameFirst;
String nameLast;
System.out.print("First Name: ");
nameFirst = Keyboard.readString();
System.out.print("Last Name: ");
nameLast = Keyboard.readString();
System.out.print("Enter Grade: ");
grade = Keyboard.readInt();
}
并且,我的第二个类应该在第一类方法中获取数据,因此我可以格式化并正确显示它。
public class FormatUserData
{
int avg; //avg of grades
int grade; //user input grade
int totalGrades; //total of grade
public static void updateGrades(String [] args)
{
...
}
...
}
现在,这就是我遇到的问题,我需要将用户从UserData类输入的等级提升到FormatUserData类中,我不确定如何。
答案 0 :(得分:1)
如果我理解正确,你应该在第二节中设置setter和constructor。
public class FormatUserData
{
String name;
int avg; //avg of grades
int grade; //user input grade
int totalGrades; //total of grade
public FormatUserData(String name,int a, int g, int tg) {
avg = a;
grade = g;
totalGrades = tg;
}
public void setGrades(int g)
{
grade = g;
}
.......................
你应该在main方法()
中创建一个实例public class UserData
{
public static void main (String [] args)
{
int grade;
String nameFirst;
String nameLast;
System.out.print("First Name: ");
nameFirst = Keyboard.readString();
System.out.print("Last Name: ");
nameLast = Keyboard.readString();
System.out.print("Enter Grade: ");
grade = Keyboard.readInt();
FormatUserData fud = new FormatUserData(nameFirst +" "+ namesecond , grade);
}
您可以将Tostring()方法写入Format类以显示字符串
public String toString() {
.........
}