toString方法用于数组

huangapple go评论81阅读模式
英文:

toString method for arrays

问题

import java.util.ArrayList;
import java.util.Arrays;

public class Suitcase {
    private ArrayList<Item> items = new ArrayList<>();
    private final int maxWeight;
    private int[] arr = new int[items.size()];

    public Suitcase(int maxWeight) {
        this.maxWeight = maxWeight;
    }

    public void addItem(Item item) {
       int itemsWeight = 0;
       for(Item i: items){
           itemsWeight += i.getWeight();
       }
       if(itemsWeight + item.getWeight() <= this.maxWeight){
            items.add(item);
       }
   }

    public void array() {
        for(Item item: items){
            int index = item.getWeight();
            this.arr[index] += 1;
        }
    }

    public String toString() {
        String returnValue = "";
        for(int i = 0; i < arr.length; i++){
            returnValue = arr[i] + " items " + i + " kg";
        }
        return returnValue;
    }
}

public class Item {
    private int weight;
    private String name;

    public Item(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }
    public String getName() {
        return this.name;
    }
    public int getWeight() {
        return this.weight;
    }
    public String toString() {
        return this.name + "(" + String.valueOf(this.weight) + ")";
    }
}

public class Main {
    public static void main(String[] args) {
        Item book = new Item("Lord of the rings", 2);
        Item phone = new Item("Nokia 3210", 1);
        Item brick = new Item("brick", 4);

        Suitcase suitcase = new Suitcase(5);
        System.out.println(suitcase.toString());

        suitcase.addItem(book);
        System.out.println(suitcase);

        suitcase.addItem(phone);
        System.out.println(suitcase);

        suitcase.addItem(brick);
        System.out.println(suitcase);
    }
}
英文:

I am struggling with an actually very easy task, which is print out items from an item array like:

arr[3,4,2,5]

0 items (0 kg)

0 items (1 kg)

0 items (2 kg)

and so on.
This is what I have done, but my program will not print anything toString方法用于数组 Heeelp me please.

import java.util.ArrayList;
import java.util.Arrays;
public class Suitcase {
private ArrayList&lt;Item&gt; items = new ArrayList&lt;&gt;();
private final int maxWeight;
private int[] arr = new int[items.size()];
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
int itemsWeight = 0;
for(Item i: items){
itemsWeight += i.getWeight();
}
if(itemsWeight + item.getWeight() &lt;= this.maxWeight){
items.add(item);
}
}
public void array() {
for(Item item: items){
int index = item.getWeight();
this.arr[index] += 1;
}
}
public String toString() {
String returnValue = &quot;&quot;;
for(int i = 0; i &lt; arr.length; i++){
returnValue = arr[i] + &quot; items &quot; + i + &quot; kg&quot;;
}
return returnValue;
}
}
public class Item {
private int weight;
private String name;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public String toString() {
return this.name + &quot;(&quot; + String.valueOf(this.weight) + &quot;)&quot;;
}
}

Here is my main class, but it will not print anything:

public class Main {
public static void main(String[] args) {
Item book = new Item(&quot;Lord of the rings&quot;, 2);
Item phone = new Item(&quot;Nokia 3210&quot;, 1);
Item brick = new Item(&quot;brick&quot;, 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase.toString());
suitcase.addItem(book);
System.out.println(suitcase);
suitcase.addItem(phone);
System.out.println(suitcase);
suitcase.addItem(brick);
System.out.println(suitcase);
}
}

答案1

得分: 1

请确保修改您的 "toString()" 函数,目前它只打印最后一个值,请将其修改为:

public String toString(){
    String returnValue = "";
    for(int i = 0; i<arr.length;i++ ){
        returnValue += arr[i] + " 项 " + i + " 公斤"; // 注意是 '+='
    }
    return returnValue;
}
英文:

Make sure to change your "toString()" function, currently it is only printing the last value, change it to:

public String toString(){
String returnValue =&quot;&quot;;
for(int i = 0; i&lt;arr.length;i++ ){
returnValue += arr[i] + &quot; items &quot; +i+&quot; kg&quot;; //notice its &#39;+=&#39;
}
return returnValue;
}

答案2

得分: 1

import java.util.ArrayList;

class Suitcase {

	private ArrayList<Item> items = new ArrayList<>();
	private final int maxWeight;
	private int totalWeight;

	public Suitcase(int maxWeight) {
		this.maxWeight = maxWeight;
	}

	public void addItem(Item item) {
		if (totalWeight + item.getWeight() <= maxWeight) {
			int index = items.indexOf(item);
			if (index == -1) {
				items.add(item);
			}
			totalWeight += item.getWeight();
			item.setCount(item.getCount() + 1);
			System.out.println(item.getName() + " was added in the suitcase");
		} else {
			System.out.println(item.getName() + " can not be accommodated in the suitcase.");
		}
	}

	public String toString() {
		String returnValue = "";
		for (Item item : items) {
			returnValue += "No. of " + item.getName() + " in the suitcase = " + item.getCount()
					+ ", its total weight = " + item.getCount() * item.getWeight() + "kg\n";
		}
		if (returnValue.isEmpty()) {
			returnValue = "The suitcase is empty.";
		} else {
			returnValue += "Total weight of the suitcase = " + totalWeight + "kg";
		}
		return returnValue;
	}
}

class Item {
	private int weight;
	private String name;
	private int count;

	public Item(String name, int weight) {
		this.name = name;
		this.weight = weight;
	}

	public String getName() {
		return this.name;
	}

	public int getWeight() {
		return this.weight;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	@Override
	public String toString() {
		return "Item [weight=" + weight + ", name=" + name + ", count=" + count + "]";
	}
}

public class Main {
	public static void main(String[] args) {
		Item book = new Item("Lord of the rings", 2);
		Item phone = new Item("Nokia 3210", 1);
		Item brick = new Item("brick", 4);

		Suitcase suitcase = new Suitcase(5);
		System.out.println(suitcase);

		suitcase.addItem(book);
		suitcase.addItem(phone);
		suitcase.addItem(brick);
		suitcase.addItem(phone);
		suitcase.addItem(book);
		System.out.println(suitcase);
	}
}
英文:

Notes:

  1. You do not need to call suitcase.toString() while printing the suitcase object. When System.out.println(suitcase); is implicitly gets converted into System.out.println(suitcase.toString());.
  2. You can make your design simpler by having a variable to keep track of the total weight in the suitcase. Also, create a variable in Item to keep track of item's count in the suitcase.
  3. You do not need int[] arr. It is simply adding unwanted complexity. Remove it.
  4. It is better to use enhanced for loop if you can do so.

Given below is the code incorporating the points mentioned above:

import java.util.ArrayList;
class Suitcase {
private ArrayList&lt;Item&gt; items = new ArrayList&lt;&gt;();
private final int maxWeight;
private int totalWeight;
public Suitcase(int maxWeight) {
this.maxWeight = maxWeight;
}
public void addItem(Item item) {
if (totalWeight + item.getWeight() &lt;= maxWeight) {
int index = items.indexOf(item);
if (index == -1) {// It means the item does not exist in the suitcase
items.add(item);
}
// If the item already exists, do not add it&#39;s entry again; just update its
// count and the totalWeight of the suitcase
totalWeight += item.getWeight();
item.setCount(item.getCount() + 1);
System.out.println(item.getName() + &quot; was added in the suitcase&quot;);
} else {
System.out.println(item.getName() + &quot; can not be accommodated in the suitcase.&quot;);
}
}
public String toString() {
String returnValue = &quot;&quot;;
for (Item item : items) {
returnValue += &quot;No. of &quot; + item.getName() + &quot; in the suitcase = &quot; + item.getCount()
+ &quot;, its total weight = &quot; + item.getCount() * item.getWeight() + &quot;kg\n&quot;;
}
if (returnValue.isEmpty()) {
returnValue = &quot;The suitcase is empty.&quot;;
} else {
returnValue += &quot;Total weight of the suitcase = &quot; + totalWeight + &quot;kg&quot;;
}
return returnValue;
}
}
class Item {
private int weight;
private String name;
private int count;
public Item(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return &quot;Item [weight=&quot; + weight + &quot;, name=&quot; + name + &quot;, count=&quot; + count + &quot;]&quot;;
}
}
public class Main {
public static void main(String[] args) {
Item book = new Item(&quot;Lord of the rings&quot;, 2);
Item phone = new Item(&quot;Nokia 3210&quot;, 1);
Item brick = new Item(&quot;brick&quot;, 4);
Suitcase suitcase = new Suitcase(5);
System.out.println(suitcase);
suitcase.addItem(book);
suitcase.addItem(phone);
suitcase.addItem(brick);
suitcase.addItem(phone);
suitcase.addItem(book);
System.out.println(suitcase);
}
}

Output:

The suitcase is empty.
Lord of the rings was added in the suitcase
Nokia 3210 was added in the suitcase
brick can not be accommodated in the suitcase.
Nokia 3210 was added in the suitcase
Lord of the rings can not be accommodated in the suitcase.
No. of Lord of the rings in the suitcase = 1, its total weight = 2kg
No. of Nokia 3210 in the suitcase = 2, its total weight = 2kg
Total weight of the suitcase = 4kg

答案3

得分: 0

你用值0初始化了你的arr。注意,new ArrayList()的初始大小为0。看一下这个示例:

import java.util.ArrayList;

class Main {
  private static ArrayList<Object> items = new ArrayList();
  private static int[] arr = new int[items.size()];
  public static void main(String[] args) {
    System.out.println(items.size()); // => 0
    System.out.println(arr.length); // => 0
  }
}

因此,当你调用System.out.println(suitcase)时,在SuitcasetoString()方法中的for循环将会遍历0个元素,因此不会输出任何内容。

英文:

You initialize your arr with value 0. Note that the initial size of new ArrayList() is 0. Take a look at this example:

import java.util.ArrayList;
class Main {
private static ArrayList&lt;Object&gt; items = new ArrayList();
private static int[] arr = new int[items.size()];
public static void main(String[] args) {
System.out.println(items.size()); # =&gt; 0
System.out.println(arr.length); # =&gt; 0
}
}

As a result when you call System.out.println(suitcase) the for loop in Suitcase's toString() method iterates over exactly 0 elements - therefore not outputting anything.

huangapple
  • 本文由 发表于 2020年4月7日 23:54:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/61084157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定