我是一名初级 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
类需要能够访问ProductType
的Map
,其中键是名称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/