ENUMS-USER-INPUT-DATE-TIME-FILE-HANDLING.PDF

Summary

This document provides examples of Java programming, covering concepts like enums, user input, date and time, and file handling. It demonstrates different syntax for creating and using enums, dealing with various data types, working with dates and times, and manipulating files.

Full Transcript

Enums } { An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should b...

Enums } { An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters: } Example enum Level { You can access enum constants with a “dot” LOW, MEDIUM, syntax. HIGH } Level myVar = Level.MEDIUM; Enum is short for “enumerations” which In the code above, we created an enum called Level. You may notice that the values of this enum are all written in means “specifically listed”. uppercase – this is just a general convention. You will not get an error if the values are lowercase. Enum inside a Class You can also have an enum inside a class: public class Main { enum Level { LOW, MEDIUM, } HIGH The output will be? public static void main(String[] args) { Level myVar = Level.MEDIUM; System.out.println(myVar); } } Enum in a Switch Statement enum Level { LOW, MEDIUM, HIGH Enums are often used } public class Main { public static void main(String[] args) { in switch statement Level myVar = Level.MEDIUM; s to check for switch(myVar) { case LOW: corresponding System.out.println("Low level"); break; values: case MEDIUM: System.out.println("Medium level"); break; case HIGH: System.out.println("High level"); break; } } } Loop Through an Enum The enum type has a values() method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum: enum Level { LOW, MEDIUM, HIGH, } public class Main { public static void main(String[] args) { for (Level myVar : Level.values()) { System.out.println(myVar); } } } Difference between Enums and Classes An enum can, just like a class, have attributes and methods. The only difference is that enum constants are public, static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces). // Define the interface interface Actionable { // Usage void performAction(); } public class Main { public static void main(String[] args) { // Define the enum implementing the interface enum Task implements Actionable { for (Task task : Task.values()) { System.out.print(task.name() + ": "); CLEAN { task.performAction(); public void performAction() { } System.out.println("Cleaning in progress..."); } } } }, Explanation: WASH { 1.Interface Definition: The Actionable interface is created with the public void performAction() { method performAction. System.out.println("Washing in progress..."); 2.Enum Implementation: The Task enum implements the } Actionable interface. Each constant provides its specific }, implementation for the performAction method. COOK { 3.Dynamic Behavior: When performAction is called on a Task public void performAction() { constant, the respective implementation is executed. System.out.println("Cooking in progress..."); } Output of the Example: } } CLEAN: Cleaning in progress... WASH: Washing in progress... COOK: Cooking in progress... Why And When To Use Enums? Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc. Exercise How can you access enum constants? What is an enum?  A special class that represents a group of constants Consider the following code: enum Level { LOW, MEDIUM, HIGH } Fill in the missing part below to loop through the constants of the Level enum: for (Level myVar : Level. ) { System.out.println(myVar); } Java User Input (Scanner) import java.util.Scanner; // Import the Scanner class Java User Input class Main { public static void main(String[] args) { The Scanner class is used to get user input. Scanner myObj = new Scanner(System.in); // Create a To use the Scanner class, create Scanner object an object of the class and use System.out.println("Enter username"); any of the available methods found in the Scanner class String userName = myObj.nextLine(); // Read user documentation. In our example, input we will use System.out.println("Username is: " + userName); // the nextLine() method, which is Output user input used to read Strings: } } Input Types In the previous example, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below: Method Description nextBoolean() Reads a boolean value from the user nextByte() Reads a byte value from the user nextDouble() Reads a double value from the user nextFloat() Reads a float value from the user nextInt() Reads a int value from the user nextLine() Reads a String value from the user nextLong() Reads a long value from the user nextShort() Reads a short value from the user Integer Input from the User The nextInt() method is used to take input of an integer from the user. //Example Importing the class import java.util.Scanner; In the following example, we are taking an integer as an input − public class IntegerInput { public static void main(String[] args) { // Creating an object of Scanner class Scanner sc = new Scanner(System.in); // Reading an Integer Input System.out.print("Input an integer value: "); int int_num = sc.nextInt(); System.out.print("The input is : " + int_num); } } In the example below, we use different methods to read data of various types: import java.util.Scanner; class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = myObj.nextLine(); // Numerical input int age = myObj.nextInt(); double salary = myObj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } } Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like "InputMismatchException"). Exercise What is a correct syntax to create a Scanner object? Class Scan = new Scanner(System.in); Scanner myObj = new Scanner(System.in); Main myObj = new Main(Scanner); Scan myObj = new Scan(Scanner); Fill in the missing parts to import the java.util.Scanner class from the Java API:... ; Which method is used to read Strings from input? The nextLine() method The Scanner() method The readString() method The userInput() method Which method is used to read integers from input? The nextLine() method The integer() method The nextInt() method The readInt() method Activity: Employee Management System In this activity, users will be able to enter different types of information about an employee: name (String), age (int), salary (double), and employee status (boolean). Then, the program will display the details of the employee. Output: Objective: Input Types: String, int, double, boolean. Enter employee name: John Doe Output: Display the entered information. Enter employee age: 30 Enter employee salary: 55000.75 Step-by-Step Instructions: Is the employee active? (true/false): true 1.Create a new Java class called EmployeeManagementSystem. 2.Use the following Java input types: Employee Details: String for employee name. Name: John Doe int for employee age. Age: 30 double for employee salary. Salary: $55000.75 boolean for employee status (active or inactive).Active: Yes Date and Time Java Dates Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example: Class Description LocalDate Represents a date (year, month, day (yyyy-MM-dd)) LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm- ss-ns)) LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) DateTimeFormatter Formatter for displaying and parsing date-time objects How to Display Current Date? To display the current date, import the java.time.LocalDate class, and use its now() method: import java.time.LocalDate; // import the LocalDate class public class Main { public static void main(String[] args) { LocalDate myObj = LocalDate.now(); // Create a date object System.out.println(myObj); // Display the current date } } How to Display Current Time? To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method: import java.time.LocalTime; // import the LocalTime class public class Main { public static void main(String[] args) { LocalTime myObj = LocalTime.now(); // Create a date object System.out.println(myObj); // Display the current date } } How to Display Current Date and Time? To display the current date and time, import the java.time.LocalDateTime class, and use its now() method: import java.time.LocalDateTime; // import the LocalDateTime class public class Main { public static void main(String[] args) { LocalDateTime myObj = LocalDateTime.now(); // Create a date object System.out.println(myObj); // Display the current date and time } } Formatting Date and Time The "T" in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date- time objects. The following example will remove both the "T" and nanoseconds from the date-time: import java.time.LocalDateTime; // Import the LocalDateTime class import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class public class Main { public static void main(String[] args) { LocalDateTime myDateObj = LocalDateTime.now(); System.out.println("Before formatting: " + myDateObj); DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); String formattedDate = myDateObj.format(myFormatObj); System.out.println("After formatting: " + formattedDate); } } The output will be: The output will be: Before Formatting: 2024-11-24T07:45:24.135874 After Formatting: 24-11-2024 07:45:24 The ofPattern() method accepts all sorts of values, if you want to display the date and time in a different format. For example: Value Example yyyy-MM-dd "1988-09-29" dd/MM/yyyy "29/09/1988" dd-MMM-yyyy "29-Sep-1988" E, MMM dd yyyy "Thu, Sep 29 1988" Exercise What is a correct syntax to create a Date object? a. NextDate myObj = new Date(now); b. Date myObj = new DateTime(); c. Date myObj = new Date(); d. LocalDate myObj = LocalDate.now(); Which package can be imported to work with date and time? The java.time package The java.datetimes package The java.dates package The java.scantime Which class can be used to display the current date and time? The LocalDateTime class The LocalTime class The OfPattern class The LocalDate class How to Get the Month of a Day The term "Month of Day" can be interpreted in several ways, but it likely relates to formatting or working with dates to extract the month or represent a day within a month. You can extract the month from a date using LocalDate or LocalDateTime from the java.time package. Example: import java.time.LocalDate; import java.time.Month; Output: Month: NOVEMBER public class MonthOfDayExample { Month Value: 11 public static void main(String[] args) { // Current date LocalDate today = LocalDate.now(); // Get the month Month month = today.getMonth(); // Returns Month enum (e.g., NOVEMBER) int monthValue = today.getMonthValue(); // Returns the month number (e.g., 11) System.out.println("Month: " + month); System.out.println("Month Value: " + monthValue); How to Get the Day of the Month You can extract the day within a month using the getDayOfMonth() method. Example: import java.time.LocalDate; Output: public class DayOfMonthExample { Day of the Month: 28 public static void main(String[] args) { // Current date LocalDate today = LocalDate.now(); // Get the day of the month int dayOfMonth = today.getDayOfMonth(); System.out.println("Day of the Month: " + dayOfMonth); } } Format as "Month Day" If you want to format a date to display something like "November 28", use a DateTimeFormatter. Example: import java.time.LocalDate; import java.time.format.DateTimeFormatter;Output: public class MonthDayFormatExample { Formatted Date: November 28 public static void main(String[] args) { // Current date LocalDate today = LocalDate.now(); // Format date as "Month Day" DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd"); String formattedDate = today.format(formatter); Summary of Key Methods: Method Description Example Output getMonth() Gets the month as an enum NOVEMBER getMonthValue() Gets the month as a number 11 getDayOfMonth() Gets the day within the month 28 DateTimeFormatter.ofPattern(" Formats as "Month Day" November 28 MMMM dd") FILE HANDLING File handling is an important part of any application. Java has several methods for creating, reading, updating, and deleting files. Java File Handling The File class from the java.io package, allows us to work with files. To use the File class, create an object of the class, and specify the filename or directory name: Example import java.io.File; // Import the File class File myObj = new File("filename.txt"); // Specify the filename The File class has many useful methods for creating and getting information about files. For example: Method Type Description canRead() Boolean Tests whether the file is readable or not canWrite() Boolean Tests whether the file is writable or not createNewFile() Boolean Creates an empty file delete() Boolean Deletes a file exists() Boolean Tests whether the file exists getName() String Returns the name of the file getAbsolutePath() String Returns the absolute pathname of the file length() Long Returns the size of the file in bytes list() String[] Returns an array of the files in the directory mkdir() Boolean Creates a directory Create and Write To Files Create a File To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason): Example: import java.io.File; // Import the File class //Used to create a File object, which represents a file or directory path. import java.io.IOException; // Import the IOException class to handle errors //Handles errors that might occur during file operations (e.g., when file creation fails). public class CreateFile { public static void main(String[] args) { try { File myObj = new File("filename.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { The output will be: System.out.println("File already exists."); File created: filename.txt } } catch (IOException e) { // Handles potential errors (e.g., file creation failed due to permission issues or invalid file paths). System.out.println("An error occurred."); e.printStackTrace(); // This prints the detailed stack trace of the exception, showing the exact sequence of method calls that led to the error. } } } To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt import java.io.File; import java.io.IOException; public class CreateFileDir { public static void main(String[] args) { try { File myObj = new File("C:\\Users\\Client\\Desktop\\OOP\\filename.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } Write To a File In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method: import java.io.FileWriter; // Import the FileWriter class import java.io.IOException; // Import the IOException class to handle errors The output will be: public class WriteToFile { Successfully wrote to the file. public static void main(String[] args) { try { FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); Read a File In the previous chapter, you learned how to create and write to a file. In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter: import java.io.File; // Import the File class import java.io.FileNotFoundException; // Import this class to handle errors import java.util.Scanner; // Import the Scanner class to read text files public class ReadFile { public static void main(String[] args) { try { File myObj = new File("filename.txt"); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { String data = myReader.nextLine(); The output will be: System.out.println(data); Files in Java might be tricky, but it is fun enough! } myReader.close(); } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } Get File Information import java.io.File; // Import the File class To get more information about a file, use any of the File methods: public class GetFileInfo { public static void main(String[] args) { The output will be: File myObj = new File("filename.txt"); File name: filename.txt if (myObj.exists()) { Absolute path: C:\Users\MyName\filename.txt Writeable: true System.out.println("File name: " + myObj.getName()); Readable: true File size in bytes: 0 System.out.println("Absolute path: " + myObj.getAbsolutePath()); System.out.println("Writeable: " + myObj.canWrite()); System.out.println("Readable " + myObj.canRead()); System.out.println("File size in bytes " + myObj.length()); } else { System.out.println("The file does not exist."); } } } Note: There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream, etc. Which one to use depends on the Java version you're working with and whether you need to read bytes or characters, and the size of the file/lines etc. Delete Files To delete a file in Java, use the delete() method: import java.io.File; // Import the File class public class DeleteFile { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.delete()) { The output will be: Deleted the file: filename.txt System.out.println("Deleted the file: " + myObj.getName()); } else { System.out.println("Failed to delete the file."); } } } Delete a Folder You can also delete a folder. However, it must be empty: import java.io.File; public class DeleteFolder { public static void main(String[] args) { File myObj = new File("C:\\Users\\MyName\\Test"); The output will be: Deleted the folder: Test if (myObj.delete()) { System.out.println("Deleted the folder: " + myObj.getName()); } else { System.out.println("Failed to delete the folder."); } }

Use Quizgecko on...
Browser
Browser