有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java不能做我的系统。出来println(Item.toString());?

我已经重写了类对象的toString方法,但我的方法不起作用,我不知道为什么。下面是我的方法的代码(在一个名为ShoppingBag的类中):

public String toString(){ 
    String str = ""; 
    Item temp = record;  
    str += "\n\nThe bag contains:\n"; 
    str += String.format("%-18s%-13s%-12s\n", "Name of the Items", "Quantity", "Subtotal"); 
    while(temp != null){ 
        str += String.format("%-18s%-13s%-12s\n", temp.getItemName(), temp.getQuantity(),
           "$"+(temp.getRetailPrice()*temp.getQuantity()));
    }
    str += String.format("%-18s%-13s%-12s\n", "", "Total:", "$"+this.totalCost()); 
    str += String.format("%-18s%-13s%-12s\n", "", "Tax(5%):", "$"+(this.totalCost()
          * taxRate)); 
    str += String.format("%-18s%-13s%-12s\n", "", "Grand Total:", "$"+this.totalCost()
          +(this.totalCost()*taxRate)); 
    String test = "test1";
    return test;
}

我知道里面有很多垃圾和类项和字符串。总体安排编译或运行时没有例外,它只是不打印任何内容

在我的应用程序中,我尝试以下方法:

ShoppingBag bag = new ShoppingBag(parameters);
System.out.println(bag.toString());

没有指纹。当我注释掉方法(String test = "test1"; return test;)的最后两行以外的所有内容时,它会打印“test1”,但其他文本块不应该影响测试变量,所以我不明白为什么它不会打印其他内容


共 (1) 个答案

  1. # 1 楼答案

    因为你被困在一个无限循环中,所以没有任何东西可以打印;这个:

    while(temp != null){ 
        str += String.format("%-18s%-13s%-12s\n", temp.getItemName(), temp.getQuantity(), "$"+(temp.getRetailPrice()*temp.getQuantity()));
    }
    

    temp永远不会是null,所以你永远不会跳出这个循环

    这就是为什么当您删除这些行时,它开始工作(您删除了无限循环)。您应该删除while循环。您可能打算将其改为if语句(以避免NullPointerException)。总而言之,您可能是指if (temp != null)而不是while (temp != null)tutorial on ^{}语句,tutorial on ^{}语句)

    也可以考虑使用{a3}来代替所有的字符串连接。