我是面向对象编程的新手,所以我不知道如何在字符串中返回此计算的结果。我正在寻找这样的输出:
约翰的信用评级为187。
我的问题是信用似乎没有被计算或与对象无关。我应该从calcCredit方法返回一些值吗?
public class Person
{
private String name;
private int age;
private double rating;
public Person(String name, int age)
{
}
public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public void calcCredit()
{
//credit calculation would go here, for my purpose a static number right now.
rating = 500;
}
//method to returns the status
public String findStatus()
{
//return my desired output
}
public class CreditDemo
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name: ");
String n = keyboard.nextLine();
System.out.print("Enter the age: ");
int a = keyboard.nextInt();
Person user = new Person(n, a);
//how do I call findStatus to get the credit associated with the user?
}
}
}
答案 0 :(得分:1)
将其作为calcCredit()方法:
public int calcCredit()
{
int credit = 500;
//Do some more calculations on credit here
return credit;
}
像这样实施:
Person user = new Person(n, a);
String status = user.findStatus();
int credit = user.calcCredit();
System.out.println("This person's status is " + status);
System.out.println("Their credit is " + credit);
答案 1 :(得分:1)
您应该使用 getter 方法从类中获取数据。另外,另一种方法是计算相关数据并立即返回。以下是基于Person
类的示例:
public class Person {
//current fields
public double getCredit() {
double credit = ...; //calculations here
//return the value of this variable to clients
return credit;
}
}
然后,在您的客户端代码中,调用此方法并使用数据:
public class CreditDemo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name: ");
String n = keyboard.nextLine();
System.out.print("Enter the age: ");
int a = keyboard.nextInt();
Person user = new Person(n, a);
//how do I call findStatus to get the credit associated with the user?
double credit = user.getCredit();
System.out.println("Credit for " + user.getName() + " is: " + credit);
}
}
答案 2 :(得分:1)
您忘记使用参数初始化构造函数中的变量。
至于你的问题,你可以按如下方式定义findStatus()方法,
public String findStatus() {
return "The credit rating of " + name + " is " + rating;
}
在main方法中,您可以调用以下方法来打印结果,
System.out.println(user.findStatus());
由于你已经设定了名称和年龄的方法,也许为一个人的特定属性定义'get'方法也是一个好主意,只是一个想法。
答案 3 :(得分:0)
现在您已经创建了一个人,接下来应该计算他的信用评级。为此,请致电
user.calcCredit();
然后你需要打印出他的状态。你可以这样做:
System.out.println("The credit rating of John is " + user.getStatus());
获得您的信用,在类Person:
中创建一个公共方法public int getCredit() {
return this.credit;
}
然后你可以在main方法中调用user.getCredit()来打印值。