Book Image

Java Fundamentals

By : Gazihan Alankus, Rogério Theodoro de Brito, Basheer Ahamed Fazal, Vinicius Isola, Miles Obare
Book Image

Java Fundamentals

By: Gazihan Alankus, Rogério Theodoro de Brito, Basheer Ahamed Fazal, Vinicius Isola, Miles Obare

Overview of this book

Since its inception, Java has stormed the programming world. Its features and functionalities provide developers with the tools needed to write robust cross-platform applications. Java Fundamentals introduces you to these tools and functionalities that will enable you to create Java programs. The book begins with an introduction to the language, its philosophy, and evolution over time, until the latest release. You'll learn how the javac/java tools work and what Java packages are - the way a Java program is usually organized. Once you are comfortable with this, you'll be introduced to advanced concepts of the language, such as control flow keywords. You'll explore object-oriented programming and the part it plays in making Java what it is. In the concluding chapters, you'll get to grips with classes, typecasting, and interfaces, and understand the use of data structures, arrays, strings, handling exceptions, and creating generics. By the end of this book, you will have learned to write programs, automate tasks, and follow advanced courses on algorithms and data structures or explore more advanced Java courses.
Table of Contents (12 chapters)
Java Fundamentals
Preface

Lesson 3: Control Flow


Activity 6: Controlling the Flow of Execution Using Conditionals

Solution:

  1. Create a class named Salary and add main() method:

    public class Salary {
       public static void main(String args[]) { 
  2. Initialize two variables workerhours and salary.

    int workerhours = 10; 
    double salary = 0;
  3. In the if condition, check whether the working hours of the worker is below the required hours. If the condition holds true, then the salary should be (working hours * 10).

    if (workerhours <= 8 ) 
    salary = workerhours*10;
  4. Use the else if statement to check if the working hours lies between 8 hours and 12 hours. If that is true, then the salary should be calculated at $10 per hour for the first eight hours and the remaining hours should be calculated at $12 per hour.

    else if((workerhours > 8) && (workerhours < 12)) 
    salary = 8*10 + (workerhours - 8) * 12;
  5. Use the else block for the default of $160 (additional day's salary) per day.

    else
        salary = 160;
    System.out.println("The worker's salary is " + salary);
    }
    }

Activity 7: Developing a Temperature System

Solution:

  1. Declare two strings, temp and weatherWarning, and then initialize temp with either High, Low, or Humid.

    public class TempSystem
    {
        public static void main(String[] args) {
            String temp = "Low";
            String weatherWarning;
  2. Create a switch statement that checks the different cases of temp, and then initialize the variable weatherWarning to appropriate messages for each case of temp (High, Low, Humid).

    switch (temp) { 
            case "High": 
                weatherWarning = "It's hot outside, do not forget sunblock."; 
                break; 
            case "Low": 
                weatherWarning = "It's cold outside, do not forget your coat."; 
                break; 
            case "Humid": 
                weatherWarning = "The weather is humid, open your windows."; 
                break;
  3. In the default case, initialize weatherWarning to "The weather looks good. Take a walk outside".

    default: 
      weatherWarning = "The weather looks good. Take a walk outside"; 
      break;
  4. After you complete the switch construct, print the value of weatherWarning.

    } 
            System.out.println(weatherWarning); 
        }
    }
  5. Run the program to see the output, it should be similar to:

    It's cold outside, do not forget your coat.

    Full code is as follows:

    public class TempSystem
    {
        public static void main(String[] args) {
            String temp = "Low";
            String weatherWarning;
                switch (temp) { 
            case "High": 
                weatherWarning = "It's hot outside, do not forget sunblock."; 
                break; 
            case "Low": 
                weatherWarning = "It's cold outside, do not forget your coat."; 
                break; 
            case "Humid": 
                weatherWarning = "The weather is humid, open your windows."; 
                break; 
            
            default: 
                weatherWarning = "The weather looks good. Take a walk outside"; 
                break; 
            } 
            System.out.println(weatherWarning); 
        }
    }

Activity 8: Implementing the for Loop

Solution:

  1. Right-click the src folder and select New | Class.

  2. Enter PeachBoxCounter as the class name, and then click OK.

  3. Import the java.util.Scanner package:

    import java.util.Scanner;
  4. In the main() enter the following:

    public class PeachBoxCounter
    {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
    System.out.print("Enter the number of peaches picked: ");
    int numberOfPeaches = sc.nextInt();
    for (int numShipped = 0; numShipped < numberOfPeaches; numShipped += 20)      {
    System.out.printf("shipped %d peaches so far\n", numShipped);
    }
    }
    }

Activity 9: Implementing the while Loop

Solution:

  1. Right-click the src folder and select New | Class.

  2. Enter PeachBoxCounters as the class name, and then click OK.

  3. Import the java.util.Scanner package:

    import java.util.Scanner;
  4. In the main() enter the following:

    public class PeachBoxCounters{
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.print("Enter the number of peaches picked: ");
        int numberOfPeaches = sc.nextInt();
        int numberOfBoxesShipped = 0;
    
        while (numberOfPeaches >= 20) {
            numberOfPeaches -= 20;
            numberOfBoxesShipped += 1;
            System.out.printf("%d boxes shipped, %d peaches remaining\n", 
                    numberOfBoxesShipped, numberOfPeaches);
        }
    }
    }

Activity 10: Implementing Looping Constructs

Solution:

  1. Import the packages that are required to read data from the user.

    import java.util.Scanner;
    public class Theater {
    public static void main(String[] args)
  2. Declare the variables to store the total number of seats available, remaining seats, and tickets requested.

    {
    int total = 10, request = 0, remaining = 10;
  3. Within a while loop, implement the if else loop that checks whether the request is valid, which implies that the number of tickets requested is less than the number of seats remaining.

    while (remaining>=0)
    {
    System.out.println("Enter the number of tickets");
    Scanner in = new Scanner(System.in);
    request = in.nextInt();
  4. If the logic in the previous step is true, then print a message to denote that the ticket is processed, set the remaining seats to the appropriate value, and ask for the next set of tickets.

    if(request <= remaining)
    {
    System.out.println("Your " + request +" tickets have been procced. Please pay and enjoy the show.");
    remaining = remaining - request;
    request = 0;
    }
  5. If the logic in step 3 is false, then print an appropriate message and break out of the loop:

    else
    {
    System.out.println("Sorry your request could not be processed");
    break;
    }
    }
    }
    }

Activity 11: Continuous Peach Shipment with Nested Loops

Solution:

  1. Right-click the src folder and select New | Class.

  2. Enter PeachBoxCounter as the class name, and then click OK.

  3. Import the java.util.Scanner package:

    import java.util.Scanner;
  4. In the main() enter the following:

    public class PeachBoxCount{    
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int numberOfBoxesShipped = 0;
        int numberOfPeaches = 0;
        while (true) {
            System.out.print("Enter the number of peaches picked: ");
            int incomingNumberOfPeaches = sc.nextInt();
            if (incomingNumberOfPeaches == 0) {
                break;
            }
            numberOfPeaches += incomingNumberOfPeaches;
            while (numberOfPeaches >= 20) {
                numberOfPeaches -= 20;
                numberOfBoxesShipped += 1;
                System.out.printf("%d boxes shipped, %d peaches remaining\n",
                        numberOfBoxesShipped, numberOfPeaches);
            }
        }
    }
    }