有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法添加包含货币的字符串

我的代码中有两个错误,我不知道如何解决

请给他们看看,告诉我该怎么做

以下是我的应用程序的代码:

public class Food {

String price = null;
String name = null;
boolean selected = false;

public Food(String price, String name, boolean selected) {
    super();
    this.price = price;
    this.name = name;
    this.selected = selected;
}

public String getPrice() {
    return price;
}
public void setPrice(String price) {
    this.price = price;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

public boolean isSelected() {
    return selected;
}
public void setSelected(boolean selected) {
    this.selected = selected;
}

}

public class MainActivity extends Activity {

    MyCustomAdapter dataAdapter = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Generate list View from ArrayList
        displayListView();
        checkButtonClick();
    }

    private void displayListView() {

        //Array list of foods
        ArrayList<Food> foodList = new ArrayList<Food>();
        Food food = new Food("15 SAR", "Chicken Meal", false);
        foodList.add(food);
        food = new Food("10 SAR", "Sliced Chicken", false);
        foodList.add(food);
        food = new Food("20 SAR", "Sandwich Chicken", false);
        foodList.add(food);
        food = new Food("10 SAR", "Hot Chicken", false);
        foodList.add(food);
        food = new Food("6 SAR", "Grilled potatoes", false);
        foodList.add(food);
        food = new Food("2 SAR", "Pepsi", false);
        foodList.add(food);
        food = new Food("17 SAR", "Fish Meal", false);
        foodList.add(food);

        //create an ArrayAdaptar from the String Array
        dataAdapter = new MyCustomAdapter(this,
                R.layout.food_info, foodList);
        ListView listView = (ListView) findViewById(R.id.listView1);
        // Assign adapter to ListView
        listView.setAdapter(dataAdapter);

    }

    private class MyCustomAdapter extends ArrayAdapter<Food> {

        private ArrayList<Food> foodList;

        public MyCustomAdapter(Context context, int textViewResourceId,
                               ArrayList<Food> foodList) {
            super(context, textViewResourceId, foodList);
            this.foodList = new ArrayList<Food>();
            this.foodList.addAll(foodList);

        }

        private class ViewHolder {
            TextView price;
            CheckBox name;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder = null;
            Log.v("ConvertView", String.valueOf(position));

            if (convertView == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(
                        Context.LAYOUT_INFLATER_SERVICE);
                convertView = vi.inflate(R.layout.food_info, null);

                holder = new ViewHolder();
                holder.price = (TextView) convertView.findViewById(R.id.price);
                holder.name = (CheckBox) convertView.findViewById(R.id.checkBox);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            Food food = foodList.get(position);
            holder.price.setText(" (" + food.getPrice() + ")");
            holder.name.setText(food.getName());
            holder.name.setChecked(food.isSelected());

            holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    food.setSelected(b);
                }
            });
            holder.name.setTag(food);

            return convertView;

        }

    }

    private void checkButtonClick() {

        Button myButton = (Button) findViewById(R.id.findSelected);
        myButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                setContentView(R.layout.invoic_page);
                int totalPrice = 0;
                for (Food f : foodList) {
                    if (f.isSelected) {
                        totalPrice += f.getPrice();
                    }

                    //totalPrice variable now has the total of all selected items
                }
            }

        });
    }
}

我试图尽我所能解决它们,但其他错误出现在代码的不同位置,所以我想要最好的解决方案


共 (2) 个答案

  1. # 1 楼答案

    第二个货币问题是String。你不能简单地添加"1 SAR""2 SAR"然后期望得到"3 SAR"

    如果这是一个单一货币系统,不要在任何地方附加" SAR",也不要使用字符串来存储值,无论是int还是long,并存储货币的最低分割,例如halalas

    new Food("15 SAR", "Chicken Meal", false);变成new Food(1500, "Chicken Meal", false);

    然后向用户显示价格:

    String forDisplay = String.format("%.2f SAR", totalHalas/100);
    

    或者,特别是如果这是一个多货币系统,请为您的货币创建一个类:

    就我个人而言,我会用图书馆来做这个:Joda Money

    但你也可以自己玩:

    public class Money {
       private final String currency;
       private final long value;
       private final int dp;
    
       public Money(long value, int dp, String currency){
           this.value = value;
           this.dp = dp;
           this.currency = currency;
       }
    
       //optional helper factory method
       public static Money sar(long halas){
           return new Money(halas, 2, "SAR");
       }
    
       public Money add(Money other){
           if(!other.currency.equals(currency))
               throw new RuntimeException("Can't add different currencies");
           if(!other.dp.equals(dp))
               throw new RuntimeException("The decimal places do not match");
           return new Money(value + other.value, dp, currency);
       }
    
       public String toString(){
           return String.format("%."+dp+"f %s", value/Math.pow(10,dp), currency);
       }
    }
    

    用法示例:

    System.out.println(new Money(1500,2,"SAR").add(new Money(623,2,"SAR")));
    //or:
    System.out.println(Money.sar(1500).add(Money.sar(623)));
    

    Outputs

    21.23 SAR
    
  2. # 2 楼答案

    totalPriceint,在Food模型类中priceString。所以你需要换衣服

    for (Food f : foodList) {
                if (f.isSelected) {
                    totalPrice += Integer.parseInt(f.getPrice());
                }
    
                //totalPrice variable now has the total of all selected items
            }
    

    而且final Food food = foodList.get(position);需要定义最终的