Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mgminterview;
- import java.util.ArrayList;
- import java.util.Arrays;
- //Your task is to:
- //- fix the code
- //- improve the poor quality of this code.
- //
- //(You can change anything you want
- //
- //The class should sort food instances and output the following lines:
- //
- //Potato 1
- //Potato 9
- //Potato 11
- //Tomato 11
- //Potato 12
- //Potato 42
- //Potato 46
- //Potato 55
- //Potato 77
- //Tomato 121
- //
- public class MgmInterviewFoodSort {
- public FOOD[] foods;
- public static abstract class FOOD implements Comparable<FOOD> {
- public int size;
- public String name;
- public FOOD () {
- this.size = -1;
- }
- public FOOD (int size) {
- this.size = size;
- }
- public int getSize() {
- return this.size;
- }
- public String getName() {
- return this.name;
- }
- //sort the food by their size and then alphabetically by type
- public int compareTo (FOOD other) {
- if (this.getSize() < other.getSize()) {
- return -1;
- }
- if (this.getSize() == other.getSize()) {
- if (this.getName().compareTo(other.getName()) < 0) {
- return -1;
- }
- if (this.getName().compareTo(other.getName()) > 0) {
- return 1;
- }
- return 0;
- }
- return 1;
- }
- }
- public static class Potato extends FOOD {
- public Potato () {
- this.name = "Potato";
- }
- public Potato (int size) {
- super(size);
- this.name = "Potato";
- }
- public int getSize () {
- return this.size;
- }
- public String getName () {
- return this.name;
- }
- public String toString () {
- return this.getName() + " " + this.getSize();
- }
- }
- public static class Tomato extends FOOD {
- public Tomato () {
- this.size = 121;
- this.name = "Tomato";
- }
- public Tomato (int size) {
- super(size);
- this.name = "Tomato";
- }
- public int getSize () {
- return this.size;
- }
- public String getName () {
- return this.name;
- }
- public String toString () {
- return this.getName() + " " + this.getSize();
- }
- }
- public static void print(FOOD[] foods) {
- for (int x=0; x< foods.length; x++) {
- System.out.println(foods[x].toString());
- }
- }
- public static void main(final String[] args) {
- FOOD[] foods = new FOOD[10];
- foods[0] = new Tomato(11);
- foods[1] = new Tomato();
- foods[2] = new Potato(1);
- foods[3] = new Potato(42);
- foods[4] = new Potato(77);
- foods[5] = new Potato(55);
- foods[6] = new Potato(46);
- foods[7] = new Potato(12);
- foods[8] = new Potato(11);
- foods[9] = new Potato(9);
- Arrays.sort(foods);
- print(foods);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement