Using compareTo to sort one array in ascending order

So I have to create an array of 5 chocolates, but I have to order them based on their quantities. I am not allowed to use the sort function.

import java.util.Scanner;

import java.util.Random;

public class Chocolate {

private String name;

private int quantity;

public Chocolate(String cName, int cQuantity) { = cName;

this.quantity = cQuantity;


public String getName() {

return name;


public int getQuantity() {

return quantity;


public int compareTo(Chocolate obj1){

if(this.quantity < obj1.quantity)

return -1;

else if (this.quantity > obj1.quantity)

return 1;


return 0;


public static void main(String args[]) {

Chocolate[] ch = new Chocolate[5];

Random rand = new Random();

Scanner scan = new Scanner(;

String name;

int result;

int quantity;

for (int i =...

Read More »

By: StackOverFlow - Wednesday, 7 November

Related Posts