gpt4 book ai didi

Java [基础] 对象问题

转载 作者:行者123 更新时间:2023-12-01 07:38:00 26 4
gpt4 key购买 nike

对模糊的标题表示歉意,因为我想不出这个名字是什么。

基本上创建一个计算学生财务付款的小程序。当我运行它时,它计算对象限额没有问题。然而,无论我尝试什么,对象“助学金”似乎除了 0 之外什么也没有提出。

代码如下:

import java.util.Scanner;

public class studentFinance implements Payment {
private String stuname, department, course;
private float budget, allowance, bursary;
private int id, currentbudget, attendance;
private double numbofcourses;

// student name, id, department, course enrolledon, attendance, bursary,allowance

//course and numbofcourses already read in
Scanner in = new Scanner(System.in);

public studentFinance(float currentBudget) {
budget = currentbudget;
}

public float amendBudget(float newbudget) {
budget = newbudget;//Transfer data from parameter to instance variable
return budget;//Return statement
}

public float calcPayment() {
//stuname,department,numbofcourses,attendance,id

System.out.println("Please enter the student name");
stuname = in.next();
System.out.println("Please enter the department name");
department = in.next();
System.out.println("Please enter the number of numbofcourses");
numbofcourses = in.nextDouble();
System.out.println("Please enter the attendance");
attendance = in.nextInt();
System.out.println("Please enter their ID number");
id = in.nextInt();
System.out.println("Enter HND,HNC or NC");
course = in.next();

if (attendance > 95 & numbofcourses >= 6) {
allowance = 1000;
} else if (attendance > 85 & numbofcourses >5) {
allowance = (1000 * .75F);
} else if (attendance > 75 & numbofcourses >= 4) {
allowance = (1000 * .5F);
} else if (attendance > 75 & numbofcourses >= 3) {
allowance = 100;
} else {
allowance = 0;
}

if(course=="HND") {
bursary = 250;
} else if(course=="HNC") {
bursary = 200;
} else if(course=="NC") {
bursary = 100;
} else {
bursary = 0;
}

return bursary + allowance;
}

double payment;

public void makePayment() {
System.out.println("The allowance total is : " + payment);
payment = bursuary + allowance;
}

public void print() {

}


}

如果有任何用途,这是用于界面的代码,还有其他元素,但我认为它们与这里无关。

interface Payment {
public float amendBudget(float budget);
public float calcPayment();
public void makePayment();
public void print();
}

感谢任何帮助。

最佳答案

== 并没有像你想象的那样做。 == (当应用于对象时)只是检查两个对象是否是同一个对象,而不是它们的内容是否相等,因此它不适用于此处的字符串。你想要的是:

if("HND".equals(course)) {
// ...
} else if ("HNC".equals(course)) {
// ...
} // etc

通常,在处理基元(intfloat 等)时,您只想使用 == 你明确只是想看看两个变量是否指向完全相同的对象。

您也可以将它们写为:

if(course.equals("HND")) {}

但我更喜欢在常量上使用.equals,因为你知道它们永远不会是null。这可能不是您关心的问题,但这只是我已经习惯的模式。

关于Java [基础] 对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9098549/

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