首页 > 解决方案 > JOptionPane 不打印方法 for 循环变量

问题描述

我有这个方法叫做“cambiar”,我从一个叫做“articulos”的数组中接收数据,然后我把那个数据放在我的“datos”变量中。但输出只是打印如下内容:

选择你想改xx的文章(我用这个xx字作为参考)

我的代码没有打印“datos”变量,我不知道为什么。

public ArrayList<Item> cambiar() {
        
    String datos = "\n";
    int cantidad;
    String nombre;
    for (int i = 0; i < articulos.size(); i++) {
        cantidad = articulos.get(i).getCantidad();
        nombre = articulos.get(i).getP().getNombre();
        datos = "Articulo: " + nombre + ", Cantidad:" + cantidad + "\n";
    }
    int art = Integer.parseInt(JOptionPane.showInputDialog(null,"Select which article you would like to change\n"+ datos+"xx"));
    articulos.get(art);
    articulos.get(art).getCantidad();
    int cuan = Integer.parseInt(JOptionPane.showInputDialog(null, "How many would you like buy?"));
    articulos.get(art).setCantidad(cuan);
    return articulos;
}

标签: javafor-loopjoptionpane

解决方案


我看到一些可能是问题的行:

  1. 该行articulos.get(art);不执行任何操作,因此我建议将其删除。
  2. 在这条线上 datos = "Articulo: " + nombre + ", Cantidad:" + cantidad + "\n";有2个问题。第一个是我假设你想显示所有 exsts 文章,所以你需要替换=by+=以将所有字符串添加到一个。第二个是你在\nin 中使用JOptionPane,这是行不通的。在JOptionPane中,您可以仅使用 HTML 而不是 java String 语法来设置您的消息样式。您可以通过"<html>"在您的消息之前添加(以及更多可重复的代码,"</html>"在此之后)来做到这一点,除了替换 all "\n"in "</br>". 例如:
public ArrayList<Item> cambiar() {
        
    String datos = "<br/>";
    int cantidad;
    String nombre;
    for (int i = 0; i < articulos.size(); i++) {
        cantidad = articulos.get(i).getCantidad();
        nombre = articulos.get(i).getP().getNombre();
        datos += "Articulo: " + nombre + ", Cantidad:" + cantidad + "<br/>";
    }
    int art = Integer.parseInt(JOptionPane.showInputDialog(null,"<html>Select which article you would like to change<br/>"+ datos+"xx</html>"));
    articulos.get(art);
    articulos.get(art).getCantidad();
    int cuan = Integer.parseInt(JOptionPane.showInputDialog(null, "How many would you like buy?"));
    articulos.get(art).setCantidad(cuan);
    return articulos;
}

推荐阅读