字符串比较不成功,计算总计为0

时间:2013-04-07 10:03:35

标签: java inheritance

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

问题是什么?

CollegeCourse.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;
  // }
}

LabCourse.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");
}
}

UseCourse.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);
   }
 } 

2 个答案:

答案 0 :(得分: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"))

Reference

修改

另一个问题是你永远不会设置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也一样。

答案 1 :(得分:0)

我不确定,但您确切地设定了实验课的费用?是的,比较字符串必须使用String.equals()而不是使用==。

Java comparison with == of two strings is false?