Advertisement
Guest User

LAB3 LAB4

a guest
Nov 17th, 2017
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 29.04 KB | None | 0 0
  1. === LAB.3 PICERIJA ===
  2.  
  3. import java.util.Scanner;
  4. import java.util.*;
  5.  
  6. class InvalidExtraTypeException extends Exception{
  7.     public InvalidExtraTypeException(String message){
  8.         super(message);
  9.     }
  10. }
  11. class InvalidPizzaTypeException extends Exception{
  12.     public InvalidPizzaTypeException(String message){
  13.         super(message);
  14.     }
  15. }
  16. class ItemOutOfStockException extends Exception{
  17.     public ItemOutOfStockException(Item item){
  18.     }
  19. }
  20. class ArrayIndexOutOfBoundsException extends Exception{
  21.     public ArrayIndexOutOfBoundsException(int i){}
  22. }
  23. class EmptyOrderException extends Exception{
  24.     public EmptyOrderException(String message){
  25.         super(message);
  26.     }
  27. }
  28. class OrderLockedException extends Exception{
  29.    
  30. }
  31.  
  32. interface Item {
  33.     public int getPrice();
  34.     public String getType();
  35. }
  36. class ExtraItem implements Item{
  37.     String type;
  38.     public ExtraItem(String _type) throws InvalidExtraTypeException{
  39.         if( _type.equals("Ketchup") || _type.equals("Coke"))
  40.             type = _type;
  41.         else
  42.             throw new InvalidExtraTypeException(_type);
  43.        
  44.     }
  45.     public int getPrice(){
  46.         if (type.equals("Ketchup")) return 3;
  47.         if (type.equals("Coke")) return 5;
  48.         return 0;
  49.     }
  50.     public String getType(){
  51.         return type;
  52.     }
  53. }
  54. class PizzaItem implements Item{
  55.     String type;
  56.     public PizzaItem(String _type) throws InvalidPizzaTypeException{
  57.         if(_type.equals("Standard") || _type.equals("Pepperoni") || _type.equals("Vegetarian"))
  58.             type = _type;
  59.         else
  60.             throw new InvalidPizzaTypeException(_type);
  61.     }
  62.     public int getPrice(){
  63.         if (type.equals("Standard")) return 10;
  64.         if (type.equals("Pepperoni")) return 12;
  65.         if (type.equals("Vegetarian")) return 8;
  66.         return 0;
  67.     }
  68.     public String getType(){
  69.         return type;
  70.     }
  71. }
  72.  
  73. class Order{
  74.     List<Item> list;
  75.     List<Integer> listCount;
  76.     boolean locked = false;
  77.     public Order(){
  78.         list = new ArrayList<Item>();
  79.         listCount = new ArrayList<Integer>();
  80.     }
  81.     public void addItem(Item item, int count) throws Exception{
  82.         if (locked == true) throw new OrderLockedException();
  83.         if (count > 10) throw new ItemOutOfStockException(item);
  84.         int index = -1;
  85.         for(int i = 0; i < list.size(); i++){
  86.             if(list.get(i).getType().equals(item.getType())){
  87.                 index = i;
  88.                 break;
  89.             }
  90.         }
  91.         if ( index == -1 ){
  92.             list.add(item);
  93.             listCount.add(count);
  94.         }
  95.         else {
  96.             listCount.set(index, count);
  97.         }
  98.     }
  99.     public int getPrice(){
  100.         int sum = 0;
  101.         for (int i = 0; i < list.size(); i++){
  102.             sum += list.get(i).getPrice()*listCount.get(i);
  103.         }
  104.         return sum;
  105.     }
  106.     public void displayOrder(){
  107.         for(int i = 0; i < list.size(); i++){
  108.             System.out.format("%3d.%-15sx%2d%5d$\n",i+1,list.get(i).getType(),listCount.get(i).intValue(),listCount.get(i).intValue()*list.get(i).getPrice());
  109.         }
  110.         System.out.format("%-22s%5d$\n","Total:",this.getPrice());
  111.     }
  112.     public void lock() throws EmptyOrderException {
  113.         try{
  114.             if (list.size() == 0) throw new EmptyOrderException("EmptyOrder");
  115.             locked = true;
  116.         }catch(Exception e){
  117.             System.out.println(e.getMessage());
  118.         }
  119.     }
  120.     public void removeItem(int index) throws Exception{
  121.         if (locked == true) throw new OrderLockedException();
  122.         if(index < 0 || index > list.size()-1) throw new ArrayIndexOutOfBoundsException(index);
  123.         list.remove(index);
  124.         listCount.remove(index);
  125.     }
  126. }
  127.  
  128. public class PizzaOrderTest {
  129.  
  130.     public static void main(String[] args) {
  131.         Scanner jin = new Scanner(System.in);
  132.         int k = jin.nextInt();
  133.         if (k == 0) { //test Item
  134.             try {
  135.                 String type = jin.next();
  136.                 String name = jin.next();
  137.                 Item item = null;
  138.                 if (type.equals("Pizza")) item = new PizzaItem(name);
  139.                 else item = new ExtraItem(name);
  140.                 System.out.println(item.getPrice());
  141.             } catch (Exception e) {
  142.                 System.out.println(e.getClass().getSimpleName());
  143.             }
  144.         }
  145.         if (k == 1) { // test simple order
  146.             Order order = new Order();
  147.             while (true) {
  148.                 try {
  149.                     String type = jin.next();
  150.                     String name = jin.next();
  151.                     Item item = null;
  152.                     if (type.equals("Pizza")) item = new PizzaItem(name);
  153.                     else item = new ExtraItem(name);
  154.                     if (!jin.hasNextInt()) break;
  155.                     order.addItem(item, jin.nextInt());
  156.                 } catch (Exception e) {
  157.                     System.out.println(e.getClass().getSimpleName());
  158.                 }
  159.             }
  160.             jin.next();
  161.             System.out.println(order.getPrice());
  162.             order.displayOrder();
  163.             while (true) {
  164.                 try {
  165.                     String type = jin.next();
  166.                     String name = jin.next();
  167.                     Item item = null;
  168.                     if (type.equals("Pizza")) item = new PizzaItem(name);
  169.                     else item = new ExtraItem(name);
  170.                     if (!jin.hasNextInt()) break;
  171.                     order.addItem(item, jin.nextInt());
  172.                 } catch (Exception e) {
  173.                    System.out.println(e.getClass().getSimpleName());
  174.                 }
  175.             }
  176.             System.out.println(order.getPrice());
  177.             order.displayOrder();
  178.         }
  179.         if (k == 2) { // test order with removing
  180.             Order order = new Order();
  181.             while (true) {
  182.                 try {
  183.                     String type = jin.next();
  184.                     String name = jin.next();
  185.                     Item item = null;
  186.                     if (type.equals("Pizza")) item = new PizzaItem(name);
  187.                     else item = new ExtraItem(name);
  188.                     if (!jin.hasNextInt()) break;
  189.                     order.addItem(item, jin.nextInt());
  190.                 } catch (Exception e) {
  191.                     System.out.println(e.getClass().getSimpleName());
  192.                 }
  193.             }
  194.             jin.next();
  195.             System.out.println(order.getPrice());
  196.             order.displayOrder();
  197.             while (jin.hasNextInt()) {
  198.                 try {
  199.                     int idx = jin.nextInt();
  200.                     order.removeItem(idx);
  201.                 } catch (Exception e) {
  202.                     System.out.println(e.getClass().getSimpleName());
  203.                 }
  204.             }
  205.             System.out.println(order.getPrice());
  206.             order.displayOrder();
  207.         }
  208.         if (k == 3) { //test locking & exceptions
  209.             Order order = new Order();
  210.             try {
  211.                 order.lock();
  212.             } catch (Exception e) {
  213.                 System.out.println(e.getClass().getSimpleName());
  214.             }
  215.             try {
  216.                 order.addItem(new ExtraItem("Coke"), 1);
  217.             } catch (Exception e) {
  218.                 System.out.println(e.getClass().getSimpleName());
  219.             }
  220.             try {
  221.                 order.lock();
  222.             } catch (Exception e) {
  223.                 System.out.println(e.getClass().getSimpleName());
  224.             }
  225.             try {
  226.                 order.removeItem(0);
  227.             } catch (Exception e) {
  228.                 System.out.println(e.getClass().getSimpleName());
  229.             }
  230.         }
  231.     }
  232.  
  233. }
  234.  
  235.  
  236. === LAB.3 TELEFONSKI IMENIK ===
  237.  
  238. import java.util.*;
  239. import java.io.*;
  240. //21:59
  241. class InvalidNumberException extends Exception{
  242.      public InvalidNumberException() {
  243.             super("InvalidNumberException");
  244.         }
  245.        
  246.         public InvalidNumberException(String message) {
  247.             super(message);
  248.         }
  249. }
  250. class InvalidNameException extends Exception{
  251.      String name;
  252.        
  253.         public InvalidNameException(String name) {
  254.             super("InvalidNameException");
  255.                     this.name = name;
  256.      
  257.         }
  258. }
  259. class MaximumSizeExceddedException extends Exception{
  260.     public MaximumSizeExceddedException() {
  261.         super("MaximumSizeExceddedException");
  262.     }
  263.     public MaximumSizeExceddedException(String message) {
  264.         super(message);
  265.     }
  266. }
  267. class InvalidFormatException extends Exception{
  268.     public InvalidFormatException() {
  269.         super("InvalidFormatException");
  270.     }
  271.    
  272.     public InvalidFormatException(String message) {
  273.         super(message);
  274.     }
  275. }
  276. class Contact{
  277.     protected String name;
  278.     protected String [] phones;
  279.     public Contact(String _name, String ..._phonenumber) throws InvalidNumberException, InvalidNameException, MaximumSizeExceddedException{
  280.         name = setName(_name);
  281.         if (_phonenumber.length > 5)
  282.             throw new MaximumSizeExceddedException();
  283.         phones = new String [_phonenumber.length];
  284.         for (int i = 0; i < _phonenumber.length; i++){
  285.             phones[i] = setPhone(_phonenumber[i]);
  286.         }
  287.     }
  288.     public Contact(Contact c){
  289.         name = new String (c.name);
  290.         phones = new String[c.phones.length];
  291.         for (int i=0; i<c.phones.length; ++i)
  292.             phones[i] = new String (c.phones[i]);
  293.     }
  294.     private String setPhone(String phonenumber) throws InvalidNumberException{
  295.         if(phonenumber.length() != 9) throw new InvalidNumberException();
  296.         for(int i = 0; i < phonenumber.length(); i++){
  297.             if(!Character.isDigit(phonenumber.charAt(i)))
  298.                 throw new InvalidNumberException();
  299.         }
  300.         if (phonenumber.charAt(0) != '0' || phonenumber.charAt(1) != '7' || phonenumber.charAt(2) == '3' ||
  301.                 phonenumber.charAt(2) == '4' || phonenumber.charAt(2) == '9')
  302.             throw new InvalidNumberException();
  303.         return phonenumber;
  304.     }
  305.     private String setName(String name) throws InvalidNameException{
  306.         if(name.length()<=4 || name.length()>10) throw new InvalidNameException(name);
  307.         for(int i = 0; i <name.length();i++){
  308.             if( !Character.isAlphabetic(name.charAt(i))&&!Character.isDigit(name.charAt(i))) throw new InvalidNameException(name);
  309.         }
  310.         return name;
  311.     }
  312.     public String getName(){return name;}
  313.     public String [] getNumbers(){
  314.         String [] ret = new String [phones.length];
  315.         for(int i = 0;i < phones.length; i++){
  316.             ret[i] = new String (phones[i]);
  317.         }
  318.         Arrays.sort(ret);
  319.         return ret;
  320.     }
  321.     public void addNumber(String phonenumber) throws MaximumSizeExceddedException, InvalidNumberException{
  322.         if(phones.length == 5) throw new MaximumSizeExceddedException();
  323.         String [] temp = new String [phones.length + 1];
  324.         for(int i = 0; i <phones.length; i++)
  325.             temp[i] = phones[i];
  326.         temp[phones.length] = setPhone(phonenumber);
  327.         phones = temp;
  328.     }
  329.     public String toString(){
  330.         String ret = name+"\n"+phones.length+"\n";
  331.         String [] temp = new String [phones.length];
  332.         for(int i = 0;i < phones.length; i++){
  333.             temp[i] = new String (phones[i]);
  334.         }
  335.         Arrays.sort(temp);
  336.         for(int i = 0; i < phones.length; i++)
  337.             ret += temp[i]+"\n";
  338.         return ret;
  339.     }
  340. }
  341. class PhoneBook{
  342.     List<Contact> contacts;
  343.     public PhoneBook(){
  344.         contacts = new ArrayList<Contact>();
  345.     }
  346.     public void addContact(Contact contact) throws MaximumSizeExceddedException, InvalidNameException{
  347.         if(contacts.size() == 250) throw new MaximumSizeExceddedException();
  348.         for(int i = 0; i < contacts.size(); i++){
  349.             if(contacts.get(i).getName().equals(contact.getName())) throw new InvalidNameException(contact.getName());
  350.         }
  351.         contacts.add(contact);
  352.     }
  353.     public Contact getContactForName(String name){
  354.         for(int i = 0; i < contacts.size(); i++){
  355.             if(contacts.get(i).getName().equals(name))
  356.                 return contacts.get(i);
  357.         }
  358.         return null;
  359.     }
  360.     public int numberOfContacts(){
  361.         return contacts.size();
  362.     }
  363.    
  364.     public Contact[] getContacts(){
  365.         Contact [] temp = new Contact [contacts.size()];
  366.         for (int i = 0; i <contacts.size(); i++)
  367.             temp[i] = new Contact (contacts.get(i));
  368.         Arrays.sort(temp, new Comparator<Contact>(){
  369.             @Override
  370.             public int compare(Contact o1, Contact o2){
  371.                 if (o1.getName().compareTo(o2.getName()) < 0)
  372.                     return -1;
  373.                 else if (o1.getName().compareTo(o2.getName()) > 0)
  374.                     return 1;
  375.                 return 0;
  376.             }
  377.         });
  378.         return temp;
  379.     }
  380.     public boolean removeContact(String name){
  381.         for (int i = 0;i < contacts.size(); i++){
  382.             if(contacts.get(i).getName().equals(name)){
  383.                 contacts.remove(i);
  384.                 return true;
  385.             }
  386.         }
  387.         return false;
  388.     }
  389.     public String toString(){
  390.         StringBuilder sb = new StringBuilder();
  391.         Contact [] temp = this.getContacts();
  392.         for (Contact nowCon : temp)
  393.             sb.append(nowCon.toString()).append("\n");
  394.         return sb.toString();
  395.     }
  396.     public static boolean saveAsTextFile(PhoneBook phonebook, String path){
  397.         boolean ret = true;
  398.         try{
  399.             PrintWriter print = new PrintWriter(new FileOutputStream(path));
  400.             print.print(phonebook.toString());
  401.             print.flush();
  402.             print.close();
  403.         }catch(FileNotFoundException e){
  404.             ret = false;
  405.         }
  406.         return ret;
  407.     }
  408.     public static PhoneBook loadFromTextFile(String path) throws FileNotFoundException, IOException, InvalidFormatException{
  409.         try{
  410.             BufferedReader bf = new BufferedReader(new FileReader(path));
  411.             String line = bf.readLine();
  412.             PhoneBook pb = new PhoneBook();
  413.             while ( line != null ) {
  414.                 String name = line;
  415.                 line = bf.readLine();
  416.                
  417.                 int n = Integer.parseInt(line);
  418.                 String [] phone = new String[n];
  419.                 for (int i=0; i<n; ++i) {
  420.                     phone[i] = bf.readLine();
  421.                 }
  422.                 Contact c = new Contact(name,phone);
  423.                 pb.addContact(c);
  424.                 line = bf.readLine();
  425.             }
  426.             return pb;
  427.         }catch (InvalidNameException e) {
  428.             throw new InvalidFormatException();
  429.         } catch (MaximumSizeExceddedException e) {
  430.             throw new InvalidFormatException();
  431.         } catch (InvalidNumberException e) {
  432.             throw new InvalidFormatException();
  433.         }
  434.     }
  435.     public Contact[] getContactsForNumber(String number_prefix) {
  436.         Contact [] forn = new Contact[contacts.size()];
  437.         int k =0;
  438.         for (int i=0; i<contacts.size(); ++i) {
  439.             for (int j=0; j<contacts.get(i).getNumbers().length; ++j) {
  440.                 if (contacts.get(i).getNumbers()[j].startsWith(number_prefix)) {
  441.                     forn[k] = new Contact(contacts.get(i));
  442.                     ++k;
  443.                     break;
  444.                 }
  445.             }  
  446.         }
  447.         Contact [] help = new Contact[k];
  448.         for (int i=0; i<k; ++i) {
  449.             help[i] = new Contact(forn[i]);
  450.         }
  451.         return help;
  452.     }
  453.    
  454. }
  455.  
  456. public class PhonebookTester {
  457.  
  458.     public static void main(String[] args) throws Exception {
  459.         Scanner jin = new Scanner(System.in);
  460.         String line = jin.nextLine();
  461.         switch( line ) {
  462.             case "test_contact":
  463.                 testContact(jin);
  464.                 break;
  465.             case "test_phonebook_exceptions":
  466.                 testPhonebookExceptions(jin);
  467.                 break;
  468.             case "test_usage":
  469.                 testUsage(jin);
  470.                 break;
  471.         }
  472.     }
  473.  
  474.     private static void testFile(Scanner jin) throws Exception {
  475.         PhoneBook phonebook = new PhoneBook();
  476.         while ( jin.hasNextLine() )
  477.             phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  478.         String text_file = "phonebook.txt";
  479.         PhoneBook.saveAsTextFile(phonebook,text_file);
  480.         PhoneBook pb = PhoneBook.loadFromTextFile(text_file);
  481.         if ( ! pb.equals(phonebook) ) System.out.println("Your file saving and loading doesn't seem to work right");
  482.         else System.out.println("Your file saving and loading works great. Good job!");
  483.     }
  484.  
  485.     private static void testUsage(Scanner jin) throws Exception {
  486.         PhoneBook phonebook = new PhoneBook();
  487.         while ( jin.hasNextLine() ) {
  488.             String command = jin.nextLine();
  489.             switch ( command ) {
  490.                 case "add":
  491.                     phonebook.addContact(new Contact(jin.nextLine(),jin.nextLine().split("\\s++")));
  492.                     break;
  493.                 case "remove":
  494.                     phonebook.removeContact(jin.nextLine());
  495.                     break;
  496.                 case "print":
  497.                     System.out.println(phonebook.numberOfContacts());
  498.                     System.out.println(Arrays.toString(phonebook.getContacts()));
  499.                     System.out.println(phonebook.toString());
  500.                     break;
  501.                 case "get_name":
  502.                     System.out.println(phonebook.getContactForName(jin.nextLine()));
  503.                     break;
  504.                 case "get_number":
  505.                     System.out.println(Arrays.toString(phonebook.getContactsForNumber(jin.nextLine())));
  506.                     break;
  507.             }          
  508.         }
  509.     }
  510.  
  511.     private static void testPhonebookExceptions(Scanner jin) {
  512.         PhoneBook phonebook = new PhoneBook();
  513.         boolean exception_thrown = false;
  514.         try {
  515.             while ( jin.hasNextLine() ) {
  516.                 phonebook.addContact(new Contact(jin.nextLine()));
  517.             }
  518.         }
  519.         catch ( InvalidNameException e ) {
  520.             System.out.println(e.name);
  521.             exception_thrown = true;
  522.         }
  523.         catch ( Exception e ) {}
  524.         if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw InvalidNameException");
  525.         /*
  526.         exception_thrown = false;
  527.         try {
  528.         phonebook.addContact(new Contact(jin.nextLine()));
  529.         } catch ( MaximumSizeExceddedException e ) {
  530.             exception_thrown = true;
  531.         }
  532.         catch ( Exception e ) {}
  533.         if ( ! exception_thrown ) System.out.println("Your addContact method doesn't throw MaximumSizeExcededException");
  534.         */
  535.     }
  536.  
  537.     private static void testContact(Scanner jin) throws Exception {    
  538.         boolean exception_thrown = true;
  539.         String names_to_test[] = { "And\nrej","asd","AAAAAAAAAAAAAAAAAAAAAA","Ð�ндрејA123213","Andrej#","Andrej<3"};
  540.         for ( String name : names_to_test ) {
  541.             try {
  542.                 new Contact(name);
  543.                 exception_thrown = false;
  544.             } catch (InvalidNameException e) {
  545.                 exception_thrown = true;
  546.             }
  547.             if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNameException");
  548.         }
  549.         String numbers_to_test[] = { "+071718028","number","078asdasdasd","070asdqwe","070a56798","07045678a","123456789","074456798","073456798","079456798" };
  550.         for ( String number : numbers_to_test ) {
  551.             try {
  552.                 new Contact("Andrej",number);
  553.                 exception_thrown = false;
  554.             } catch (InvalidNumberException e) {
  555.                 exception_thrown = true;
  556.             }
  557.             if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw an InvalidNumberException");
  558.         }
  559.         String nums[] = new String[10];
  560.         for ( int i = 0 ; i < nums.length ; ++i ) nums[i] = getRandomLegitNumber();
  561.         try {
  562.             new Contact("Andrej",nums);
  563.             exception_thrown = false;
  564.         } catch (MaximumSizeExceddedException e) {
  565.             exception_thrown = true;
  566.         }
  567.         if ( ! exception_thrown ) System.out.println("Your Contact constructor doesn't throw a MaximumSizeExceddedException");
  568.         Random rnd = new Random(5);
  569.         Contact contact = new Contact("Andrej",getRandomLegitNumber(rnd),getRandomLegitNumber(rnd),getRandomLegitNumber(rnd));
  570.         System.out.println(contact.getName());
  571.         System.out.println(Arrays.toString(contact.getNumbers()));
  572.         System.out.println(contact.toString());
  573.         contact.addNumber(getRandomLegitNumber(rnd));
  574.         System.out.println(Arrays.toString(contact.getNumbers()));
  575.         System.out.println(contact.toString());
  576.         contact.addNumber(getRandomLegitNumber(rnd));
  577.         System.out.println(Arrays.toString(contact.getNumbers()));
  578.         System.out.println(contact.toString());
  579.     }
  580.  
  581.     static String[] legit_prefixes = {"070","071","072","075","076","077","078"};
  582.     static Random rnd = new Random();
  583.    
  584.     private static String getRandomLegitNumber() {
  585.         return getRandomLegitNumber(rnd);
  586.     }
  587.    
  588.     private static String getRandomLegitNumber(Random rnd) {
  589.         StringBuilder sb = new StringBuilder(legit_prefixes[rnd.nextInt(legit_prefixes.length)]);
  590.         for ( int i = 3 ; i < 9 ; ++i )
  591.             sb.append(rnd.nextInt(10));
  592.         return sb.toString();
  593.     }
  594.    
  595.  
  596. }
  597.  
  598. === LAB.4 LOCALDATE ===
  599.  
  600. import java.sql.Date;
  601. import java.sql.Timestamp;
  602. import java.time.*;
  603. import java.time.temporal.TemporalAdjusters;
  604.  
  605. /**
  606.  * LocalDate test
  607.  */
  608. public class LocalDateTest {
  609.     public static void main(String[] args) {
  610.         System.out.println(create());
  611.         System.out.println(parse());
  612.         System.out.println(with().getYear());
  613.         System.out.println(withAdjuster());
  614.         System.out.println(plus());
  615.         System.out.println(minus());
  616.         System.out.println(plusPeriod());
  617.         System.out.println(isAfter());
  618.         System.out.println(until());
  619.     }
  620.  
  621.     static LocalDate create() {
  622.         LocalDate ret = LocalDate.of(2015, 6, 18);
  623.         return ret;
  624.     }
  625.  
  626.     static LocalDate parse() {
  627.         LocalDate ret = LocalDate.parse("2015-06-18");
  628.         return ret;
  629.     }
  630.  
  631.     static LocalDate with() {
  632.         LocalDate ld = DateAndTimes.LD_20150618;
  633.         LocalDate ret = ld.with(ld);
  634.         return ret;
  635.     }
  636.  
  637.     static LocalDate withAdjuster() {
  638.         LocalDate ld = DateAndTimes.LD_20150618;
  639.         LocalDate ret = ld.with(TemporalAdjusters.firstDayOfNextYear());
  640.         return ret;
  641.     }
  642.  
  643.     static LocalDate plus() {
  644.         LocalDate ld = DateAndTimes.LD_20150618;
  645.         LocalDate ret = ld.plusMonths(10);
  646.         return ret;
  647.     }
  648.  
  649.     static LocalDate minus() {
  650.         LocalDate ld = DateAndTimes.LD_20150618;
  651.         LocalDate ret = ld.minusDays(10);
  652.         return ret;
  653.     }
  654.  
  655.     static LocalDate plusPeriod() {
  656.         LocalDate ld = DateAndTimes.LD_20150618;
  657.         LocalDate ret = ld.plusDays(3).plusMonths(2).plusYears(1);
  658.         return ret;
  659.     }
  660.  
  661.     static boolean isAfter() {
  662.         LocalDate ld = DateAndTimes.LD_20150618;
  663.         LocalDate ld2 = DateAndTimes.LD_20150807;    
  664.         boolean ret = ld2.isAfter(ld);
  665.         return ret;
  666.     }
  667.  
  668.     static Period until() {
  669.         LocalDate ld = DateAndTimes.LD_20150618;
  670.         LocalDate ld2 = DateAndTimes.LD_20150807;
  671.         Period ret = ld.until(ld2);
  672.         return ret;
  673.     }
  674.  
  675. }
  676.  
  677. class DateAndTimes {
  678.     public static final LocalDate LD_20150618 = LocalDate.of(2015, 6, 18);
  679.     public static final LocalDate LD_20150807 = LocalDate.of(2015, 8, 7);
  680. }
  681.  
  682.  
  683. === LAB.4 LOCALTIME ===
  684.  
  685. import java.time.Duration;
  686. import java.time.LocalTime;
  687. import java.time.temporal.ChronoField;
  688. import java.time.temporal.ChronoUnit;
  689.  
  690. /**
  691.  * LocalTime API tests
  692.  */
  693. public class LocalTimeTest {
  694.     public static void main(String[] args) {
  695.         System.out.println(localTimeOfHourToMinute());
  696.         System.out.println(localTimeOfHourToNanoSec());
  697.         System.out.println(localTimeParse());
  698.         System.out.println(localTimeWith());
  699.         System.out.println(localTimePlus());
  700.         System.out.println(localTimeMinus());
  701.         System.out.println(localTimeMinusDuration());
  702.         System.out.println(localDateIsBefore());
  703.         System.out.println(localTimeTruncatedTo());
  704.     }
  705.  
  706.     static LocalTime localTimeOfHourToMinute() {
  707.         LocalTime ret = LocalTime.of(23,7);
  708.         return ret;
  709.     }
  710.  
  711.     static LocalTime localTimeOfHourToNanoSec() {
  712.         LocalTime ret = LocalTime.of(23,7,3,100000000);
  713.         return ret;
  714.     }
  715.  
  716.     static LocalTime localTimeParse() {
  717.         LocalTime ret = LocalTime.parse("23:07:03.1");
  718.         return ret;
  719.     }
  720.  
  721.     static LocalTime localTimeWith() {
  722.         LocalTime lt = DateAndTimes.LT_23073050;
  723.         LocalTime ret = lt.withHour(21);
  724.         return ret;
  725.     }
  726.  
  727.     static LocalTime localTimePlus() {
  728.         LocalTime lt = DateAndTimes.LT_23073050;
  729.         LocalTime ret = lt.plusMinutes(30);
  730.         return ret;
  731.     }
  732.  
  733.     static LocalTime localTimeMinus() {
  734.         LocalTime lt = DateAndTimes.LT_23073050;
  735.         LocalTime ret = lt.minusHours(3);
  736.         return ret;
  737.     }
  738.  
  739.  
  740.     static LocalTime localTimeMinusDuration() {
  741.         LocalTime lt = DateAndTimes.LT_23073050;
  742.  
  743.         /**
  744.          * Define a {@link Duration} of 3 hours 30 minutes and 20.2 seconds
  745.          * Create a {@link LocalTime} subtracting the duration from {@link lt} by using {@link LocalTime#minus}
  746.          */
  747.         Duration dur = Duration.ofHours(3).plusMinutes(30).plusSeconds(20).plusNanos(200000000);
  748.         LocalTime ret = lt.minus(dur);
  749.         return ret;
  750.     }
  751.  
  752.     static boolean localDateIsBefore() {
  753.         LocalTime lt = DateAndTimes.LT_23073050;
  754.         LocalTime lt2 = DateAndTimes.LT_12100000;
  755.         boolean ret = lt2.isBefore(lt);
  756.         return ret;
  757.     }
  758.  
  759.     static LocalTime localTimeTruncatedTo() {
  760.         LocalTime lt = DateAndTimes.LT_23073050;
  761.         LocalTime ret = lt.truncatedTo(ChronoUnit.MINUTES);
  762.         return ret;
  763.     }
  764.  
  765.     static class DateAndTimes {
  766.         public static final LocalTime LT_23073050 = LocalTime.of(23, 7, 30, 500000000);
  767.         public static final LocalTime LT_12100000 = LocalTime.of(12, 10);
  768.     }
  769.  
  770. }
  771.  
  772. === LAB.4 LOCALDATETIME ===
  773.  
  774. import java.time.LocalDate;
  775. import java.time.LocalDateTime;
  776. import java.time.LocalTime;
  777. import java.time.format.DateTimeFormatter;
  778. import java.time.temporal.ChronoUnit;
  779. import java.time.temporal.TemporalAdjusters;
  780.  
  781. /**
  782.  * LocalDateTime tests
  783.  */
  784. public class LocalDateTimeTest {
  785.  
  786.     public static void main(String[] args) {
  787.         System.out.println(localDateTimeOf());
  788.         System.out.println(localDateTimeParse());
  789.         System.out.println(localTimeWith());
  790.         System.out.println(localDatePlusMinus());
  791.         System.out.println(localDateTimeFormat());
  792.         System.out.println(toLocalDateAndTime());
  793.         System.out.println(toLocalDateTime());
  794.     }
  795.  
  796.     static LocalDateTime localDateTimeOf() {
  797.         LocalDateTime ret = LocalDateTime.of(2015,6,20,23,7,30);
  798.         return ret;
  799.     }
  800.  
  801.     static LocalDateTime localDateTimeParse() {
  802.         LocalDateTime ret = LocalDateTime.parse("2015-06-20T23:07:30");
  803.         return ret;
  804.     }
  805.  
  806.     static LocalDateTime localTimeWith() {
  807.         LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  808.         LocalDateTime ret = ldt.with(TemporalAdjusters.firstDayOfNextMonth()).truncatedTo(ChronoUnit.HOURS);
  809.         return ret;
  810.     }
  811.  
  812.     static LocalDateTime localDatePlusMinus() {
  813.         LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  814.         LocalDateTime ret = ldt.plus(10, ChronoUnit.MONTHS).minus(5, ChronoUnit.HOURS);
  815.         return ret;
  816.     }
  817.  
  818.     static String localDateTimeFormat() {
  819.         LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  820.         String ret = ldt.format(DateTimeFormatter.ofPattern("YYYY_MM_d_HH_mm_ss"));
  821.         return ret;
  822.     }
  823.  
  824.     static String toLocalDateAndTime() {
  825.         LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  826.         LocalDate localDate = ldt.toLocalDate();
  827.         LocalTime localTime = ldt.toLocalTime();
  828.         return localDate.toString() + localTime.toString();
  829.     }
  830.  
  831.     static String toLocalDateTime() {
  832.         LocalDate ld = DateAndTimes.LD_20150618;
  833.         LocalTime lt = DateAndTimes.LT_23073050;
  834.  
  835.         /**
  836.          * Create two equal {@link LocalDateTime} from {@link ld} and {@link lt}
  837.          * by using {@link LocalDate#atTime} and {@link LocalTime#atDate}
  838.          */
  839.         LocalDateTime localDateTime1 = lt.atDate(ld);
  840.         LocalDateTime localDateTime2 = ld.atTime(lt);
  841.         return localDateTime1.toString() + " " + localDateTime2.toString();
  842.     }
  843.  
  844.     static class DateAndTimes {
  845.         public static final LocalDate LD_20150618 = LocalDate.of(2015, 6, 18);
  846.         public static final LocalTime LT_23073050 = LocalTime.of(23, 7, 30, 500000000);
  847.         public static final LocalDateTime LDT_20150618_23073050 = LocalDateTime.of(2015, 6, 18, 23, 7, 30, 500000000);
  848.     }
  849. }
  850.  
  851. === LAB.4 ZONEDDATETIME ===
  852.  
  853. import java.time.LocalDateTime;
  854. import java.time.ZoneId;
  855. import java.time.ZonedDateTime;
  856. import java.time.format.DateTimeFormatter;
  857.  
  858. /**
  859.  * ZonedDateTime tests
  860.  */
  861. public class ZonedDateTimeTest {
  862.     public static void main(String[] args) {
  863.         System.out.println(zonedDateTimeOf());
  864.         System.out.println(zonedDateTimeParse());
  865.         System.out.println(zonedDateTimeFormat());
  866.         System.out.println(toPST());
  867.         System.out.println(sameInstantAs());
  868.         System.out.println(sameLocalAs());
  869.     }
  870.  
  871.     static ZonedDateTime zonedDateTimeOf() {
  872.         ZonedDateTime ret = ZonedDateTime.of(2015,7,10,2,14,25,0,ZoneId.of("Asia/Tokyo"));
  873.         return ret;
  874.     }
  875.  
  876.     static ZonedDateTime zonedDateTimeParse() {
  877.         ZonedDateTime ret = ZonedDateTime.parse("2015-06-18T23:07:25.000+09:00[Asia/Tokyo]");
  878.         return ret;
  879.     }
  880.  
  881.     static String zonedDateTimeFormat() {
  882.         ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
  883.         String ret = zdt.format(DateTimeFormatter.ofPattern("YYYY_MM_d_HH_mm_s_z"));
  884.         return ret;
  885.     }
  886.  
  887.     static ZonedDateTime toPST() {
  888.         LocalDateTime ldt = DateAndTimes.LDT_20150618_23073050;
  889.         ZonedDateTime ret = ldt.atZone(ZoneId.of("America/Los_Angeles"));
  890.         return ret;
  891.     }
  892.  
  893.     static ZonedDateTime sameInstantAs() {
  894.         ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
  895.         ZonedDateTime ret = zdt.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
  896.         return ret;
  897.     }
  898.  
  899.     static ZonedDateTime sameLocalAs() {
  900.         ZonedDateTime zdt = DateAndTimes.ZDT_20150618_23073050;
  901.         ZonedDateTime ret = zdt.withZoneSameLocal(ZoneId.of("America/Los_Angeles"));
  902.         return ret;
  903.     }
  904.  
  905.     static class DateAndTimes {
  906.  
  907.         public static final LocalDateTime LDT_20150618_23073050 = LocalDateTime.of(2015, 6, 18, 23, 7, 30, 500000000);
  908.         public static final ZonedDateTime
  909.                 ZDT_20150618_23073050 = ZonedDateTime.of(LDT_20150618_23073050, ZoneId.of("Asia/Tokyo"));
  910.     }
  911. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement