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

时间:2017-02-11 13:20:52

标签: java android

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

请出示并告诉我该怎么做。

以下是我的应用的代码:

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
                }
            }

        });
    }
}

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

3 个答案:

答案 0 :(得分:0)

第二期钱作为String。您不能简单地添加"1 SAR""2 SAR",并希望获得"3 SAR"

如果这是单一货币系统,请勿在任何地方附加" SAR",并且不要使用字符串来存储值intlong s并存储您的货币的最低分部,例如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

答案 1 :(得分:-1)

totalPriceintFood模型类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);需要定义最终

答案 2 :(得分:-1)

对于第一个错误,您需要将food变量设为final:

// Make this final.
final Food food = foodList.get(position);
holder.name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
          food.setSelected(b);
        }
 });

对于第二个错误,您需要将String值转换为interger:

for (Food f : foodList) {
  if (f.isSelected) {
    totalPrice += Integer.valueOf(f.getPrice());
  }
}

但您最好将price变量设为整数或BigInteger以确定食物类或BigDecimal中的价格。

<强>更新

从不将您的货币保存在价格值中。相反,您可以添加一个新的变量,如货币名称。不要为了便携性和未来的无错代码而保存它。