简体   繁体   English

列出所有小于或等于X的变量

[英]List all variables that are less than or equal to X

I want to list variables such as water, popcorn, candy, juice, etc. I have around 30 variables in this list. 我想列出变量,例如水,爆米花,糖果,果汁等。此列表中大约有30个变量。 I need to set up a way that after a user inputs their total currency it will list how many of each item they can buy. 我需要建立一种方法,在用户输入总货币后,它将列出他们可以购买的每种商品的数量。 For example: 例如:

int money = user.nextint();
System.out.println("With " + money + " dollars you can buy" +
                   "# of Popcorn or # number of candy or # of juice etc");

Would a multi-dimensional array be the best way? 多维数组是最好的方法吗? I'll add a few ideas below 我将在下面添加一些想法

System.out.println("You can buy " + item1/Money + " popcorn.");

I figure I can add each item manually and divide its cost by the money. 我认为我可以手动添加每个项目,然后将其成本除以金额。 However obviously this would be extremely tedious for 30+ items and I'm just curious if there is a more effective way. 但是显然,这对于30多个项目而言将非常繁琐,而我只是好奇是否有更有效的方法。

Also I do not want to include items that are NOT affordable. 我也不想包括那些负担不起的物品。 I'd like to exclude those from my println . 我想将这些从我的println排除。 Which my only theory on that includes A LOT of if and if-else statements. 我对此的唯一理论包括很多ifif-else语句。

public class Main {
   public static  class Item {
      private double price;
      private String itemName;
      //  getter setter
   }

   public static void list( List<Item> availableItems, double money ) {
     for( Item item : availableItems ) {
         if( item.getPrice() <= money ) {
            System.out.println("You can buy " + ( int ) ( money / item.getPrice() ) + " " + item.getItemName() );
         }
     }

     // java 8 code is as below

     // availableItems.forEach( item -> { if( item.getPrice() <= money ) {
     //       System.out.println("You can buy " + ( int ) ( money / item.getPrice() ) + " " + item.getItemName() );
     //    } } );

   public static void main(String[] str ) {

       List<Item> availableItems = null;
       double money;
       // to do code for item initialization
       // get user input for money
      list ( availableItems, money );
   }
}

Write a class which holds an item and it's price. 写一个包含商品及其价格的类。 Maintain a list of items, then iterate over them and calculate the quantity for each. 维护项目清单,然后遍历它们并计算每个项目的数量。

class Item
{
    public final String name;
    public final int price;

    public Item(final String name, final int price)
    {
        this.name = name;
        this.price = price;
    }

    public int getQty(final int budget)
    {
        return budget / price;
    }
}

class Main
{
    public static void main(String... args)
    {
        final List<Item> items = Arrays.asList(
            new Item("Popcorn", 10_000), // always a rip-off
            new Item("Water", 1),
            new Item("Juice", 3)
        );

        final int money = 10;

        for (final Item item : items)
        {
            final int qty = item.getQty(money);
            if (qty > 0) // exclude things we can't buy
            {
                System.out.println("You can buy " + qty + " " + item.name);
            }
        }
    }
}

here some Code that could help you. 这里有一些可以帮助您的代码。

Item Class 物品类别

public class Item {

  private String name;
  private double price;

  public Item(String name, double price) {

    this.name = name;
    this.price = price;
  }

  public String getName() {

    return name;
  }

  public double getPrice() {

    return price;
  }
}

Main 主要

Item[] items = new Item[]{
  new Item("Popcorn", 2.5),
  new Item("Water", 1.0),
  new Item("Candy", 3.0),
  new Item("DVD", 14.5),
  ...
};

double credit = input.nextDouble();

System.out.println("Credit: " + credit + "$");

for(Item item : items) {

  if(credit > item.getPrice()) System.out.println((int) (credit / item.getPrice()) + "x " + item.getName() + "(" + item.getPrice() + "$) -> " + (credit % item.getPrice()) + "$");
}

Output 输出量

// For example    

Credit: 12.5$
5x Popcorn(2.5$) -> 0.0$
12x Water(1.0$) -> 0.5$
4x Candy(3.0$) -> 0.5$

Non-affordable items will not be issued 负担不起的物品将不会发出

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class MapTest {
    public static void main(String[] args) {
        int totalCurrency = 30;
        HashMap<String, Integer> itemsMap = new HashMap<>();
        itemsMap.put("Water", 30);
        itemsMap.put("Popcorn", 10);
        Set<Entry<String, Integer>> itemSet = itemsMap.entrySet();
        String output = "With " + totalCurrency + " dollars you can buy ";
        for (Entry entry : itemSet) {
            if ((Integer) entry.getValue() <= totalCurrency) {
                int temp = totalCurrency / (Integer) entry.getValue();
                output += temp + " of " + entry.getKey() + " ";
            }
        }
        System.out.println(output);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 给定一个列表和一个 x 的值,将其拆分,使所有小于 x 的项目排在大于或等于 x 的项目之前 - Given a list and a value of x, split it such that all items less than x came before items greater than or equal to x 将列表分为给定的相等大小X,其余列表不应小于大小Y - Split List into Given Equal Size X and remaining list should not be less than size Y 小于或等于GregorianCalendar - Less than or equal to with GregorianCalendar 少于两个变量 - Less than two variables 复制一个int数组,将所有小于x的值替换为12 - Copy an int array, replacing all values less than x with 12 有没有一种更快的方法来检查列表中的某个项目是否大于,小于或等于某个数字? - Is there a faster way to check if an item in a list if it is greater than, less than, equal to a certain number? Clojure sorted-map:找到小于或等于x的最大键(floor键) - Clojure sorted-map: find largest key that is less than or equal to x (floor key) 如何检查列表中是否存在小于等于另一个列表中元素的元素 - How to check if there exists an element in a list less than equal to element in another list JAVA中计算所有小于或等于N数的乘法表的程序 - Program that compute the multiplication table for all numbers less than or equal N in JAVA 少于运算符也要评估相等的值 - Less than operator evaluating for equal values also
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM