Java:给定参数时选择对象

标签 java class object bluej

我是一名初级 Java 程序员

现在我遇到了这个问题: 我有一个名为 Producttype 的类,其中包含一个名为 name 的字段。 我还有一个名为 Main 的类。现在,在 Main 类中,我想通过询问名称从 Producttype 类中选择一个对象。

我该怎么做?

提前致谢

产品类型代码:

import java.util.*;
import javax.swing.*;

public class Producttype
{
    //velden
    private String naam;
    private String beschrijving;
    private double aankoopprijs;
    private double verkoopprijs;
    private int aantalGekocht;
    private int aantalVerkocht;

    //constructor
    /**
     * Constructor
     */
    public Producttype(String naam, String beschrijving, double aankoopprijs, double verkoopprijs){
        this.naam = naam;
        this.beschrijving = beschrijving;
        this.aankoopprijs = aankoopprijs;
        this.verkoopprijs = verkoopprijs;
        aantalGekocht = 0;
        aantalVerkocht = 0;
    }
   public void drukInfo(){
        System.out.println("-----------------------");
        System.out.println("Naam van het product: " + naam);
        System.out.println("Beschrijving van het product: " + beschrijving);
        System.out.println("Aankoopprijs: " + aankoopprijs + " euro");
        System.out.println("Verkoopprijs: " + verkoopprijs + " euro");
        System.out.println("Aantal gekocht: " + aantalGekocht + " stuks");
        System.out.println("Aantal verkocht: " + aantalVerkocht + " stuks");
        System.out.println("");
        System.out.println("Aantal stuks in stock: " + berekenAantalInStock());
        System.out.println("");
        System.out.println("Omzet momenteel: " + berekenOmzet() + " euro");
        System.out.println("Winst momenteel: " + berekenWinst() + " euro");
    }

在我的“Main”中我得到了这个:

private void printInfoOverProducttype()
    {
        String type = JOptionPane.showInputDialog("Give the name of the producctype you want info of.");

        String info = ??????????????????????????

        System.out.println(info);
    }

我想要的是方法 printInforOverProducctype() 中的“String info”从名称等于字符串类型的对象的“Producctype”类中执行方法 drukInfo()

最佳答案

您的Main类需要能够访问ProductTypeMap,其中键是名称String >:

public class Main {
    private Map<String, ProductType> products = new ConcurrentHashMap<String, ProductType>();

    public ProductType findProductTypeByName(String name) {
        return this.products.get(name);
    }
}

关于Java:给定参数时选择对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8378314/

相关文章:

java - JOptionsPane 的默认按钮无法正常工作

java - 对一个异常禁用日志记录

java - 模拟 Runtime.getRuntime()?

java - 调试 Java 应用程序中使用的 javascript

javascript - 使用 jQuery (JavaScript) 合并对象数组中多个相同键的值

java - Android - 多个 Activity 使用一个类

javascript - 如何在同一个类中调用2个JavaScript方法?

java - 创建枚举与创建 Java 类有什么区别?

javascript - 遍历数组并将结果过滤到 10

javascript - 循环遍历 json 对象并提取数据 - js