Sunday 30 June 2013

Java Invoice Application solution

Java Problem:



Change the if/else statement so customers of type “R” with a subtotal that is greater than or equal to $250 but less than $500 get a 25% discount and those with a subtotal of $500 or more get a 30% discount.  Next, change the if/else statement so customers of type “C” always get a 20% discount.  Then, test the application to make sure this works.
Add another customer type to the if/else statement so customers of type “T” get a 40% discount for subtotals of less than $500, and a 50% discount for subtotals of $500 or more. 
Check your code to make sure that no discount is provided for a customer type code that isn’t “R”, “C”, or “T”.  Then, fix this if necessary.
Code a static method named getDiscountPercent that has two parameters:  customer type and subtotal.  To do that efficiently, you can move the appropriate code from the main method of the application to the static method and make the required modifications.
Add code that calls the static method from the body of the application.  Then, test to make sure that it works.

Java Code:

import java.text.NumberFormat;
import java.util.Scanner;

public class InvoiceApp
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String choice = "y";

        while (!choice.equalsIgnoreCase("n"))
        {
            // get the input from the user
            System.out.print("Enter customer type (r/c): ");
            String customerType = sc.next();
            System.out.print("Enter subtotal:   ");
            double subtotal = sc.nextDouble();

            // get the discount percent
            double discountPercent = 0;
            if (customerType.equalsIgnoreCase("R"))
            {
                if (subtotal < 100)
                    discountPercent = 0;
                else if (subtotal >= 100 && subtotal < 250)
                    discountPercent = .1;
                else if (subtotal >= 250)
                    discountPercent = .2;
            }
            else if (customerType.equalsIgnoreCase("C"))
            {
                if (subtotal < 250)
                    discountPercent = .2;
                else
                    discountPercent = .3;
            }
            else
                discountPercent = .1;

            // calculate the discount amount and total
            double discountAmount = subtotal * discountPercent;
            double total = subtotal - discountAmount;

            // format and display the results
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            NumberFormat percent = NumberFormat.getPercentInstance();
            System.out.println(
                "Discount percent: " + percent.format(discountPercent) + "\n" +
                "Discount amount:  " + currency.format(discountAmount) + "\n" +
                "Total:            " + currency.format(total) + "\n");

            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
        }
    }
}

Score and Average Program Java

Java Problem:



Use the += operator to increase the scoreCount and scoreTotal variables.  Then, test this to make sure that it works.
As the user enters test scores, use the methods of the Math class to keep track of the minimum and maximum scores.  When the user enters 999 to end the program, display these scores at the end of the other output data.  Now, test these changes to make sure that they work.
Change the variable that you use to total the scores from a double to an int data type.  Then, use casting to cast the score count and score total to doubles as you calculate the average score and save that average as a double.  Now, test that change.
Use the NumberFormat class to round the average score to one decimal place before displaying it at the end of the program.  

Java Code: 

import java.util.Scanner;

public class ModifiedTestScoreApp
{
    public static void main(String[] args)
    {
        // display operational messages
        System.out.println("Please enter test scores that range from 0 to 100.");
        System.out.println("To end the program enter 999.");
        System.out.println();  // print a blank line

        // initialize variables and create a Scanner object
        double scoreTotal = 0;
        int scoreCount = 0;
        int testScore = 0;
        Scanner sc = new Scanner(System.in);

        // get a series of test scores from the user
        while (testScore <= 100)
        {
            // get the input from the user
            System.out.print("Enter score: ");
            testScore = sc.nextInt();

            // accumulate score count and score total
            if (testScore <= 100)
            {
                scoreCount = scoreCount + 1;
                scoreTotal = scoreTotal + testScore;
            }
            else if (testScore == 999)
            {
                
            }
            else {
                System.out.println("Invalid entry, not counted");
               
            }
        }

        // display the score count, score total, and average score
        double averageScore = scoreTotal / scoreCount;
        String message = "\n" +
                         "Score count:   " + scoreCount + "\n"
                       + "Score total:   " + scoreTotal + "\n"
                       + "Average score: " + averageScore + "\n";
        System.out.println(message);
    }
}
---
-----------------------------
import java.util.Scanner;

public class TestScoreApp
{
    public static void main(String[] args)
    {
        // display operational messages
        System.out.println("Please enter test scores that range from 0 to 100.");
        System.out.println("To end the program enter 999.");
        System.out.println();  // print a blank line

        // initialize variables and create a Scanner object
        double scoreTotal = 0;
        int scoreCount = 0;
        int testScore = 0;
        Scanner sc = new Scanner(System.in);

        // get a series of test scores from the user
        while (testScore <= 100)
        {
            // get the input from the user
            System.out.print("Enter score: ");
            testScore = sc.nextInt();

            // accumulate score count and score total
            if (testScore <= 100)
            {
                scoreCount = scoreCount + 1;
                scoreTotal = scoreTotal + testScore;
            }
            else if (testScore == 999)
            {
                
            }
            else {
                System.out.println("Invalid entry, not counted");
               
            }
        }

        // display the score count, score total, and average score
        double averageScore = scoreTotal / scoreCount;
        String message = "\n" +
                         "Score count:   " + scoreCount + "\n"
                       + "Score total:   " + scoreTotal + "\n"
                       + "Average score: " + averageScore + "\n";
        System.out.println(message);
    }
}

Calculating Score and Average Java Program

Scoring and Calculate the Average of Score.

Java Program


Java Code:


import java.text.NumberFormat;
import java.util.Scanner;

public class ModifiedTestScoreApp
{
    public static void main(String[] args)
    {
        // display operational messages
        System.out.println("Please enter test scores that range from 0 to 100.");
        System.out.println("To end the program enter 999.");
        System.out.println();  // print a blank line

        // initialize variables and create a Scanner object
        int scoreTotal = 0;
        int scoreCount = 0;
        int testScore = 0;
        int max = 0;
        int min = 999;
        Scanner sc = new Scanner(System.in);

        // get a series of test scores from the user
        while (testScore <= 100)
        {
            // get the input from the user
            System.out.print("Enter score: ");
            testScore = sc.nextInt();

            // accumulate score count and score total
            if (testScore <= 100)
            {
                scoreCount += 1;
                scoreTotal += testScore;
                max = Math.max(max, testScore);
                min = Math.min(min, testScore);
            }
            else if (testScore == 999)
            {
                
            }
            else {
                System.out.println("Invalid entry, not counted");
               
            }
        }

        // display the score count, score total, and average score
        double averageScore = scoreTotal / scoreCount;
        averageScore = (double) scoreTotal/scoreCount;
        NumberFormat formatter = NumberFormat.getInstance();
        formatter.setMaximumFractionDigits(1);
        formatter.setMinimumFractionDigits(1);
        String output = formatter.format(averageScore);
        String message = "\n" +
                         "Score count:   " + scoreCount + "\n"
                       + "Score total:   " + scoreTotal + "\n"
                       + "Average score: " + output + "\n";
        System.out.println(message);
    }
}
-----------------------
import java.util.Scanner;

public class TestScoreApp
{
    public static void main(String[] args)
    {
        // display operational messages
        System.out.println("Please enter test scores that range from 0 to 100.");
        System.out.println("To end the program enter 999.");
        System.out.println();  // print a blank line

        // initialize variables and create a Scanner object
        double scoreTotal = 0;
        int scoreCount = 0;
        int testScore = 0;
        Scanner sc = new Scanner(System.in);

        // get a series of test scores from the user
        while (testScore <= 100)
        {
            // get the input from the user
            System.out.print("Enter score: ");
            testScore = sc.nextInt();

            // accumulate score count and score total
            if (testScore <= 100)
            {
                scoreCount = scoreCount + 1;
                scoreTotal = scoreTotal + testScore;
            }
            else if (testScore == 999)
            {
                
            }
            else {
                System.out.println("Invalid entry, not counted");
               
            }
        }

        // display the score count, score total, and average score
        double averageScore = scoreTotal / scoreCount;
        String message = "\n" +
                         "Score count:   " + scoreCount + "\n"
                       + "Score total:   " + scoreTotal + "\n"
                       + "Average score: " + averageScore + "\n";
        System.out.println(message);
    }
}

Screenshot.


Invoice Application Java Program

 Java Invoice Application


Code:


import java.text.NumberFormat;
import java.util.Scanner;

public class InvoiceApp
{
    public static double getDiscountPercent(String customerType, double subtotal){
        double discountPercent = 0;
        if (customerType.equalsIgnoreCase("R"))
        {
            if (subtotal < 100)
                discountPercent = 0;
            else if (subtotal >= 100 && subtotal < 250)
                discountPercent = .1;
            else if (subtotal >= 250 && subtotal<500)
                discountPercent = .25;
            else if (subtotal >= 500)
                discountPercent = .3;
        }
        else if (customerType.equalsIgnoreCase("T"))
        {
            if (subtotal < 500)
                discountPercent = .4;
            else if (subtotal >= 500)
                discountPercent = .5;
        }
        else if (customerType.equalsIgnoreCase("C"))
        {
            discountPercent = .2;
        }
        return discountPercent;
    }
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String choice = "y";

        while (!choice.equalsIgnoreCase("n"))
        {
            // get the input from the user
            System.out.print("Enter customer type (r/c/t): ");
            String customerType = sc.next();
            System.out.print("Enter subtotal:   ");
            double subtotal = sc.nextDouble();

            // get the discount percent
           
           
            double discountPercent = getDiscountPercent(customerType, subtotal);
            // calculate the discount amount and total
            double discountAmount = subtotal * discountPercent;
            double total = subtotal - discountAmount;

            // format and display the results
            NumberFormat currency = NumberFormat.getCurrencyInstance();
            NumberFormat percent = NumberFormat.getPercentInstance();
            System.out.println(
                "Discount percent: " + percent.format(discountPercent) + "\n" +
                "Discount amount:  " + currency.format(discountAmount) + "\n" +
                "Total:            " + currency.format(total) + "\n");

            // see if the user wants to continue
            System.out.print("Continue? (y/n): ");
            choice = sc.next();
            System.out.println();
        }
    }
}

Screenshots:

Screenshots:

 

Screenshots:

 


 

Using Interface and Polymorphism in Java Program



Using Interface and Polymorphism in Java Program

JAVA CODE:


//1.  Implements the runnable() interface
//Here interface is used by implementing the runnable at the class
public class threade implements Runnable
       {
        
       //2.  Implements the run() method of the runnable() interface to do the following:
//overriding through an Interface was used By implements the method run() with the runnable()

          
       public void run() {
              
       ////Note: The Thread.currentThread().getName() method is helpful for retrieving thread names.
              
       System.out.println(Thread.currentThread().getName()+ "running");
            
       //a.  Count down, starting with the number 5 and going to 0
       int i = 5;      
       while (i >= 0) {
                  
       ////b.  Print the name of the thread and the current value of countdown integer
                  
       //for each integer counted down
          //here polymorphism is used        
       System.out.println(Thread.currentThread().getName()+": "+i--);
               }
              
       //c.  Print "Blast Off!" when 0 is reached in the countdown
              
       System.out.println("Blast Off!");

           }  
       public static void main (String[] args)
         //Overriding - same method names with same arguments and same return types associated in a class and its subclass.
       //Overloading - same method name with different arguments, may or may not be same return type written in the same class itself.
       {
       //3.  Creates five threads in your main class giving each thread a name:
              
       //"Thread 1", "Thread 2", "Thread 3", "Thread 4", and "Thread 5"
          
       Thread thread1 = new Thread(new threade());
          
       thread1.setName("Thread 1");
          
       Thread thread2 = new Thread(new threade());
          
       thread2.setName("Thread 2");
          
       Thread thread3 = new Thread(new threade());
          
       thread3.setName("Thread 3");
          
       Thread thread4 = new Thread(new threade());
          
       thread4.setName("Thread 4");
          
       Thread thread5 = new Thread(new threade());
          
       thread5.setName("Thread 5");

          
       ////4.  Starts all five threads

          
       thread1.start();
          
       thread2.start();
          
       thread3.start();
          
       thread4.start();
          
       thread5.start();
         }
       }

Screenshots: