如何在java中返回string和double

时间:2016-06-22 10:36:11

标签: java inheritance polymorphism

您好我正在制作一个可以打印门票价格的程序。 我在回复字符串时遇到了问题。

这是我的代码

 public class DiscountTicket extends Ticket
 {
     private int numberDays;
     private int serial;
     public static double price;
     public static String s;

 public DiscountTicket(int serial, String t, int numberDays)
 {
    super(serial);
    this.numberDays = numberDays;
    s = t;
 }

 public double getPrice()
 {
    if (numberDays > 7)
    {
        price = 20.0;

    }
    else
    {
        price = 15.0;
    }

   return price ;
 }


}

如果我返回传递给我的方法的字符串。它会打印出它不兼容将double转换为字符串。我试图转换它,它只给了我0.0输出。

3 个答案:

答案 0 :(得分:0)

为了返回多个内容,您可以使用Object的数组。例如(我假设您希望getPrice()返回prices

public Object[] getPrice() {
   if (numberDays > 7)
   {
       price = 20.0;
   }
   else
   {
       price = 15.0;
   }
   Object[] array = new Object[2];
   array[0] = price;
   array[1] = s;
   return array;
}

然后你可以在返回数组后转换为Double和String。

答案 1 :(得分:0)

使用

像这样转换
     DiscountTicket discountTicket = new DiscountTicket ();

     //This gives you a string value
     String stringValueOfDouble = String.valueOf(discountTicket.getPrice());

OR

String.format()是一种新的替代方法,可用于将Double转换为String对象。它首先在Java 5(JDK1.5)中引入,并具有许多很酷的功能。

语法

 public static String format(String format, Object... args)

如何使用此方法有很多选项。但是出于转换目的,这是一个简单的例子:

示例

 double number = -895.25f;
 String numberAsString = String.format ("%f", number);

变量numberAsString的值为“-895.250000” 我们还可以控制小数位数。

   double number = -895.25f;
   System.out.println(String.format ("%.1f", number));
   System.out.println(String.format ("%.2f", number));
   System.out.println(String.format ("%.3f", number));

将显示

 -895.3
 -895.25
 -895.250

[1]

 [1]: http://i.stack.imgur.com/7t05Q.png

答案 2 :(得分:0)

public class DiscountTicket extends Ticket {

private int numberDays;
private int serial;
public static double price;
public static String s;

public DiscountTicket(int serial, String t, int numberDays) {
super(serial);
this.numberDays = numberDays;
s = t;
}

@Override
public double getPrice()
 {
    if (numberDays > 7)
    {
        price = 20.0;

    }
    else
    {
        price = 15.0;
    }

   return price ;
 }

}

public abstract class Ticket {
private int serial;

public Ticket(int serial) {
    this.serial = serial;
}

public abstract double getPrice();

public String toString() {
    return "Ticket: [serial# " + serial + " Price: " + getPrice() + "]";
}
}

  public class MainClass {

  public static void main(String args[]){

   DiscountTicket discountTicket = new DiscountTicket(5,"ashwani", 6);

    double d =  discountTicket.getPrice();

    String stringOfDouble = String.valueOf(d);



  }
}

它为我工作,检查你有其他错误