Advertisement
mmayoub

School, Remote control

Sep 26th, 2017
335
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. Remote.java
  2. -----------
  3. import java.util.Arrays;
  4.  
  5. public class Remote {
  6.     private String[] channels;
  7.  
  8.     public Remote(int size) {
  9.         channels = new String[size];
  10.         for (int i = 0; i < channels.length; i++) {
  11.             channels[i] = "";
  12.         }
  13.     }
  14.  
  15.     public boolean addChannel(String name, int index) {
  16.         if (index < channels.length && channels[index].length() == 0) {
  17.             channels[index] = name;
  18.             return true;
  19.         }
  20.  
  21.         return false;
  22.     }
  23.  
  24.     public int find(String name) {
  25.         // -1 if not found
  26.         for (int i = 0; i < channels.length; i++) {
  27.             if (channels[i].equals(name)) {
  28.                 return (i + 1);
  29.             }
  30.         }
  31.  
  32.         return -1;
  33.     }
  34.  
  35.     public void remove(String name) {
  36.         int index = find(name);
  37.         if (index != -1) {
  38.             remove(index);
  39.         }
  40.     }
  41.  
  42.     public void remove(int index) {
  43.         channels[index - 1] = "";
  44.     }
  45.  
  46.     public void sortByName() {
  47.         Arrays.sort(channels);
  48.     }
  49.  
  50.     public void move(int index1, int index2) {
  51.         String tmp = channels[index1];
  52.         channels[index1] = channels[index2];
  53.         channels[index2] = tmp;
  54.     }
  55.  
  56.     @Override
  57.     public String toString() {
  58.         String list = "";
  59.         for (int i = 0; i < channels.length; i += 1) {
  60.             list += (i + 1) + " : " + channels[i] + "\n";
  61.         }
  62.         return list;
  63.     }
  64.  
  65. }
  66.  
  67. Tester.java
  68. -----------
  69. public class Tester {
  70.  
  71.     public static void main(String[] args) {
  72.         Remote myRemote = new Remote(10);
  73.         myRemote.addChannel("MBC 4", 6);
  74.         myRemote.addChannel("zee", 1);
  75.  
  76.         System.out.println(myRemote);
  77.  
  78.         myRemote.sortByName();
  79.         System.out.println(myRemote);
  80.  
  81.     }
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement