【问题标题】:JOptionPane not printing method for-loop variableJOptionPane 不打印方法 for 循环变量
【发布时间】:2021-01-21 06:47:18
【问题描述】:

我有一个叫做“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;
}

【问题讨论】:

  • 没有minimal reproducible example,人们只能猜测您的问题是什么——正如您从问题的答案中所看到的那样。为什么不直接在方法cambiarfor 循环之前添加以下行:System.out.println(articulos.size()); 你知道,这叫做调试。

标签: java for-loop joptionpane


【解决方案1】:

好像你的文章列表是空的,for循环不是事件开始。

我不确定你想用这个方法/消息做什么,即使你设法修复你的'articulos'列表,你的'datos'变量也只会得到你列表的最后一个元素。要么使用 += 复合赋值运算符组合您的数据,要么将其余代码移动到 for 循环中(而不使用 +=),以便在每个元素上弹出对话框。

【讨论】:

    【解决方案2】:

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

    1. articulos.get(art); 行没有做任何事情,所以我建议删除它。
    2. datos = "Articulo: " + nombre + ", Cantidad:" + cantidad + "\n"; 行有 2 个问题。 第一个是我假设你想显示所有 exsts 文章,所以你需要将 = 替换为 += 以将所有字符串添加到一个。 第二个是你在\n 中使用JOptionPane,这不起作用。 在JOptionPane 中,您可以仅使用 HTML 而不是 java String 语法来设置您的消息样式。 您可以通过在您的消息之前添加"&lt;html&gt;" 来做到这一点(以及更多可重复代码,"&lt;/html&gt;"在此之后),除了替换"&lt;/br&gt;" 中的所有"\n"。 例如:
    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;
    }
    

    【讨论】:

    • 第二个是你在\n中使用JOptionPane,这样不行这是不正确的。
    • 替换“”中的所有“\n” HTML标签应为&lt;br/&gt;&lt;br&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 2011-03-17
    相关资源
    最近更新 更多