-10

我想修剪显示在第 3(Room Type)和第 4 (Meal type)列中的对象的最后 4 个字符。在底部我提供了输出示例。您可以在第 3 和第 4 列中清楚地看到最后 4 个字符是括号中的价格,这是我想要的跳闸。

public void showAll()

    {
        String name ="";
        String ID="";
        Object roomItem;
        Object mealItem;
        int roomIn;
        int meal;
        int days=0;
        double tprice=0;

        display.setText("");
        display.append("ID  Customer Name   RoomType    MealType    Days    TotalCharge($)");
        display.append("\n ---------------------------------");

        for (int i = 0; i < myList.size(); i++)
           {
        Customer c = myList.get(i);

        ID = c.getID();
        name = c.getName();
        roomIn = c.getRoomIndex();                  // Get the room index stored in Linked list
        roomItem = roomTypeCombo.getItemAt(roomIn); // Get the item stored on that index.
        meal = c.getMealIndex();                    // Get the Meal index stored in Linked list
        mealItem = mealCombo.getItemAt(meal);       // Get the item stored on that index.
        days = c.getDaysIndex();
        tprice = c.getTotalPrice();
        display.append("\n"+ID+"    "+name+"        "+roomItem+"    "+mealItem+"    "+days+ "   "+tprice);
            }
        display.append("\n \n Total "+myList.size()+" Entrie(s) !");

    } // end of function

我的程序的输出是这样的:

ID  Customer Name           RoomType    MealType    Days    TotalCharge
__________________________________________________________________

234 John Andersen       Standard($75)   Any Two($30)     4    420.0

我怎样才能绊倒Room Typeand的最后 4 个字符Meal Type

4

3 回答 3

2
String pricey = "Breakfast($10)";
String yummy = pricey.substring(0, pricey.length() - 4);
于 2012-05-07T13:34:52.930 回答
1

首先,在发布此类问题之前,您应该阅读 Java String API:http ://docs.oracle.com/javase/7/docs/api/java/lang/String.html。

然后,您可以使用类似 substring 的方法。

public String substring(int beginIndex,
               int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Examples:

     "hamburger".substring(4, 8) returns "urge"
     "smiles".substring(1, 5) returns "mile"


Parameters:
    beginIndex - the beginning index, inclusive.
    endIndex - the ending index, exclusive.
Returns:
    the specified substring.
Throws:
    IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
于 2012-05-07T13:36:59.540 回答
0

您可以使用substring()

String word = "Breakfast($10)".substring(0, "Breakfast($10)".length() - 4);
于 2012-05-07T13:34:13.003 回答