-1

如果用户从(BIO,CIS ...)中列出的类中选择一个类,LabCourse它应该给出总加实验室费用(50),但我的代码总是执行总为 0 并打印"This class don't have lab"消息

问题可能是什么?

学院课程.java

public class CollegeCourse
{
String name;
int num;
int crd;
double fee;
double total;

public CollegeCourse(String n)
  {
  name =n;
  }

public double computetotal(double fee, int crd)

    {
          fee = fee * crd;
          System.out.println("Total is $" + fee);
          this.fee=fee;
          return fee;
    }

public String getname()
  {
       return name;
  }

public int getnum()
  {
       return num;
  }

public int getcrd()
  {
       return crd;
  }
    // public double getfee()
  // {
  //       return fee;
  // }
}

实验室课程.java

public class LabCourse extends CollegeCourse
{
 double total=0;

public LabCourse(String name, double fee)
{
  super(name);
}

public void computetotal(String name)
{
   super.computetotal(fee, crd);
   if((name == "BIO") || (name == "CHM") || (name == "CIS") || (name =="PHY"))
   {
      total = fee+ 50;
      System.out.println("Total with lab is: " + total);
   }
   else 
      System.out.println("This class don't have Lab");
}
}

使用课程.java

import javax.swing.*;
import java.util.*;
import java.util.Scanner;
public class UseCourse
{
  public static void main(String args[]) throws Exception
  {
   String name;
   int num;
   int crd;
   double fee;

   Scanner inputDevice = new Scanner(System.in);

   System.out.print("Enter Department name: ");
   name = inputDevice.next();
   System.out.print("Enter Course number: ");
   num= inputDevice.nextInt();
   System.out.print("Enter Credit hours: ");
   crd = inputDevice.nextInt();
   System.out.print("Enter fee: ");
   fee = inputDevice.nextDouble();
   System.out.print("\n\n"); 

   CollegeCourse course = new CollegeCourse(name);
   course.computetotal(fee, crd);

   LabCourse full = new LabCourse(name, fee);
   full.computetotal(name);
   }
 } 
4

2 回答 2

1

字符串是类。您不应该使用==来比较类(除非您想检查它们是否是完全相同的对象(在这种情况下,不仅仅是相同的文本))

当您尝试对字符串使用时,某些 IDE(例如NetBeans)会给您一个警告。==

试试System.out.println(new String("ABC") == "ABC");- 这将打印false

改用equals

if (name.equals("BIO") || name.equals("CHM") ||
    name.equals("CIS") || name.equals("PHY"))

一个更简单的正则表达式选项:

if (name.matches("BIO|CHM|CIS|PHY"))

参考

编辑:

另一个问题是你从来没有设置LabCourse.fee,但你在这里使用它:

super.computetotal(fee, crd);

所以在构造函数中设置它:

public LabCourse(String name, double fee)
{
  super(name);
  this.fee = fee; // or add this as a parameter to CollegeCourse's constructor
}

但是,由于computetotal覆盖了费用,对它的多次调用可能无法如您所愿,因此您可能希望将其作为参数传递给computetotal

public class LabCourse extends CollegeCourse
{
  ...
  public void computetotal(String name, double fee)
  ...
}

fee这就引出了一个问题——成为一个类变量有意义吗?或者,将代码computetotal放在构造函数中并摆脱computetotal或类似的东西可能更有意义。对于name.

于 2013-04-07T10:09:39.637 回答
0

我不确定,但是你们到底在哪里设置实验课程的费用?是的,比较字符串必须使用 String.equals() 而不是 ==。

Java与两个字符串的==比较是假的?

于 2013-04-07T10:09:29.377 回答