Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store.

Question: Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as instance variables — a part number(type String), a part description(type String), a quantity of the item being purchased (type Integer) and a price per item (type Integer). Your class should have a constructor that initializes the four instance variables. Provide a property for each instance variable. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0; Use validation in the properties for these instance variables to ensure that they remain positive. In addition, provide a method named DisplayInvoiceAmount that calculates and displays the invoice amount (that is, multiplies the quantity by the price per item). How do you write an application that demonstrates the class Invoice’s capabilities?

Solution:

import java.util.Scanner;

class Invoice{

String partNumber;

String partDescription;

int itemPurchased;

double pricePerItem;

Invoice(){

partNumber = “”;

partDescription = “”;

itemPurchased = 0;

pricePerItem = 0.0;

}

String getPartNumber(){

return partNumber;

}

String getPartDescription(){

return partDescription;

}

int getItemPurchased(){

return itemPurchased;

}

double getPricePerItem(){

return pricePerItem;

}

double getInvoiceAmount(){

return (itemPurchased * pricePerItem);

}

void setPartNumber(String pn){

partNumber = pn;

}

void setPartDescription(String pd){

partDescription = pd;

}

void setItemPurchased(int ip){

itemPurchased = ip;

}

void setPricePerItem(double ppi){

pricePerItem = ppi;

}

}

class InvoiceDemo {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

Invoice invoice = new Invoice();

System.out.print(“\nEnter part number :”);

invoice.setPartNumber(sc.nextLine());

System.out.print(“Enter part description :”);

invoice.setPartDescription(sc.nextLine());

System.out.print(“Enter item purchased :”);

invoice.setItemPurchased(sc.nextInt());

System.out.print(“Enter price per item :”);

invoice.setPricePerItem(sc.nextDouble());

System.out.print(“\n\nDetail of items purchasing–>”);

System.out.print(“\nPart number :” + invoice.getPartNumber());

System.out.print(“\nPart description :” + invoice.getPartDescription());

System.out.print(“\nTotal Billing Amount :” + invoice.getInvoiceAmount());

}

A Math teacher is teaching Math course to a set of classes

A Math teacher is teaching Math course to a set of classes (each class may have different number of students) and want to check the behavior of his students in a homework report. The teacher gave the classes the same exam and marked their answer and wants to know the class whose students got the highest average.

Help the teacher in the required analysis of student’s marks by implementing a Java program ClassAverageMArks2DimmArray using 2-dimensional array to store the students marks and then compute the average of each class student’s marks. The program has the following specification:

• A Method titled averageClassMarks for computing the average (as double) of a class students marks (given to the method as a single-dimensional array)

• Another Method titled averageAliclassesMarks for computing the average (as single array of double) of all the classes class student’s marks (given to the method as a 2- dimensional array). This method has to repeatedly call the first method averageClassMarks to calculate the average of student’s marks in each class.

• The program reads from the user the number of classes and then reads the classes student’s marks (as integer values) line by line. Each line has the number of students in the class then the student’s marks.

• The program calls method averageAliclassesMarks to calculate all the average values of marks of all the classes. Again, method averageAliclassesMarks has to repeatedly call the first method averageClassMarks.

• Finally, the program then prints all the average values (rounded to 2 decimal points) of all classes student’s marks and the highest average mark as well.

 • The program has to work EXACTLY as given in the following sample run. Sample Run:

Enter number of classes: 5

Enter student’s marks of all the classes line by line such that, each line contains first the number of students in a class followed by the student’s marks:

6 50 84 76 94 62 98

5 42 64 97 88 80

6 25 35 86 47 36 75

7 59 74 96 94 82 75 98

4 88 62 56 74

Classes average marks:

Class Average

  1.   77.33
  2. 74.20
  3. 50.67
  4. 82.57
  5. 70.00

The highest average is 82.57 and it is for class 4.

==================================

Solution:

Output:

Code:

Main.java:

import java.io.*;
import java.util.*;

public class Main
{
   public static double averageClassMarks(int[] arr)
   {
       int sum=0;
       int n=arr.length;
      
       for(int i=0;i<n;i++)
       {
           sum=sum+arr[i];
       }
      
       double average=(double)sum/n;
      
       return average;
   }
   public static void averageAllClassesMarks(int[][] arr)
   {
       double highest_average=-1;
       int highest_class=0;
      
       int size=arr.length;
       System.out.println(“\nClasses average marks:”);
       System.out.println(“Class   Average”);
       for(int i=0;i<size;i++)
       {
           double average=averageClassMarks(arr[i]);
           System.out.println(i+1+”   “+String.format(“%.2f”,average));
          
           if(average>highest_average)
           {
               highest_average=average;
               highest_class=i+1;
           }
       }
      
       System.out.println(“\nThe highest average is “+String.format(“%.2f”,highest_average)+” and it is for class “+highest_class);
       System.out.println(“==================================================”);
      
   }
  
   public static void main(String[] args)
   {
       Scanner sc=new Scanner(System.in);
      
       System.out.print(“\nEnter number of classes: “);
       int n=sc.nextInt();
      
       System.out.println(“\nEnter student’s marks of all the classes line by line such that, each line contains first the number of students in a class followed by the student’s marks:\n”);
      
      
       int[][] arr=new int[n][];
      
       for(int i=0;i<n;i++)
       {
           int temp=sc.nextInt();
           arr[i]=new int[temp];
          
           for(int j=0;j<temp;j++)
           {
               arr[i][j]=sc.nextInt();
           }
       }
      
       averageAllClassesMarks(arr);
   }
}

(JAVA) Write a program called FinalTestScores.

Write a program called FinalTestScores. Ten students have taken three tests. Use an array to store the test scores. The program should ask the user to enter each student’s first name, last name, and his or her three test scores. This program should have functions that return a specific student’s first name, last name, three test scores, average tests score, and a letter grade based on the average.

Test Score Letter Grade

90-100 A

80-89 B

70-79 C

60-69 D

0-59 F

Write a class that uses a String array to hold the ten students’ names, an array of five characters to hold the five students’ letter grades, and three doubles each to hold each student’s set of test scores. Use nested loops, in which the outer loop handles the student names, and the inner loop handles the current student’s test scores. You may find using a single 10 x 3 multi-dimensional array or parallel array easier to manage instead of a separate array for each set of test scores. 

Write the following methods in the program. Print a project description that tells the user what to do.

calTestAverage — This function should accept three test scores as an argument and return the average of the test scores.

letterGrade-This function should accept test scores as an argument and return a letter grade for the test scores, based on the following grading scale.

getName-This function should accept students’ data as an argument and return a student’s name

Although averages are often floating-point values, you should cast the average test score to an integer when comparing with the grading scale. This reduces the possibility of error. Calculate students average test scores and the letter grade.

Demonstrate the class in a program that allows the user to enter each student’s name and his or her three test scores. It should then display as a table format: each student’s name, three test scores, average, and letter grade

Sample Output 

First NameLast NameTest1Test2Test3AverageGrade 
JohnSmith90.590.585.088.67 B 
BrownSam75.087.590.084.17 B
ParksPeter97.088.598.094.50A

The class average is 89.11.

PLEASE ADD COMMENTS (INLINE COMMENTS)

1. Print a descriptive message that tells the user what to do

2. Input validation

3. Method calTestAverage working properly

4. Method letterGrade working properly

5. Method getName working properly

6. Display results working Property

Solution:

import java.util.*;

class FinalTestScores
{
public static double[] calTestAverage(double scores[][])
{
double sum;
double avg[]=new double[10];
for(int i=0;i<=9;i++)
{
sum=0;
for(int j=0;j<=2;j++)
{
sum=sum+scores[i][j];
}
avg[i]=sum/3; //calculating average
}
return avg;
}


public static char[] letterGrade(double avg[])
{
char letter[]=new char[10];

// getting letter grade

for(int i=0;i<=9;i++)
{
if(avg[i]>=90 && avg[i]<100)
{
letter[i]=’A’;
}
else if(avg[i]>=80 && avg[i]<=89)
{
letter[i]=’B’;
}
else if(avg[i]>=70 && avg[i]<=79)
{
letter[i]=’C’;
}
else if(avg[i]>=60 && avg[i]<=69)
{
letter[i]=’D’;
}
else if(avg[i]>=0 && avg[i]<=59)
{
letter[i]=’E’;
}
}
return letter;
}

public static String getName()
{
Scanner sc=new Scanner(System.in);
String name=sc.nextLine(); //accepting first name and last name
return name;
}

public static void main(String args[])
{
String names[]=new String[10];
double scores[][]=new double[10][3];

Scanner sc=new Scanner(System.in);
System.out.println(“\nEnter 10 student names and their 3 test scores: \n”);

for(int i=0;i<=9;i++)
{
System.out.print(“Enter first name and last name separted by a space: “);
names[i]=getName(); // calling getName() to accept name

for(int j=0;j<=2;j++)
{
System.out.print(“Enter test score”+(j+1)+” of “+names[i]+”: “);
scores[i][j]=sc.nextDouble(); //accepting 3 test scores
}
sc.nextLine();
}

double avg[]=new double[10];
avg=calTestAverage(scores); //calling calTestAverage() to get average

char letterGrade[]=new char[10];
letterGrade=letterGrade(avg); //calling letterGrade() to letter grade

System.out.println(“\n”);
System.out.printf(“Name\t\tTest1\tTest2\tTest3\tAverage\tGrade\n”);
for(int i=0;i<=9;i++)
{
System.out.print(names[i]+”\t”); //printing names
for(int j=0;j<=2;j++)
{
System.out.print(scores[i][j]+”\t”); //displaying 3 test scores
}
System.out.printf(“%.2f\t”,avg[i]); //using printf(“%.f”) to get 2 decimal number
System.out.println(letterGrade[i]); //printing grade
}

System.out.print(“\n”);
}
}

Thinking in Java Fourth Edition Bruce Eckel Chapter 8 Exercise 4

Exercise 4: Create an abstract class with no methods. Derive a class and add a method. Create a static method that takes a reference to the base class, downcasts it to the derived class, and calls the method. In main( ), demonstrate that it works. Now put the abstract declaration for the method in the base class, thus eliminating the need for the downcast.

Solution:

abstract class NoMethods
{
}
class Extended1 extends NoMethods
{
    public void f()
    {
        System.out.println("Extended1.f");
    }
}
abstract class WithMethods
{
    abstract public void f();
}
class Extended2 extends WithMethods
{
    public void f()
    {
        System.out.println("Extended2.f");
    }
}
public class E04
{
    public static void test1(NoMethods nm)
    {
        // Must downcast to access f():
        ((Extended1)nm).f();
    }
    public static void test2(WithMethods wm)
    {
        // No downcast necessary:
        wm.f();
    }
    public static void main(String args[])
    {
        NoMethods nm = new Extended1();
        test1(nm);
        WithMethods wm = new Extended2();
        test2(wm);
    }
}

Output:

Thinking in Java Fourth Edition Bruce Eckel Chapter 8 Exercise 3

Exercise 3: Create a base class with an abstract print( ) method that is overridden in a derived class. The overridden version of the method prints the value of an int variable defined in the derived class. At the point of definition of this variable, give it a nonzero value. In the base-class constructor, call this method. In main( ), create an object of the derived type, and then call its print( ) method. Explain the results.

Solution:

abstract class BaseWithPrint
{
public BaseWithPrint()
{
print();
}
public abstract void print();
}
class DerivedWithPrint extends BaseWithPrint
{
int i = 47;
public void print()
{
System.out.println("i = " + i);
}
}
public class E03
{
public static void main(String args[])
{
DerivedWithPrint dp = new DerivedWithPrint();
dp.print();
}
}

Ouput:

Thinking in Java Fourth Edition Bruce Eckel Chapter 8 Exercise 2

Exercise 2: Create a class as abstract without including any abstract methods and verify that you cannot create any instances of that class.

Solution

public class Ex2
{
    public static void main(String[] args)
    {
        // Nogo1 and Nogo2 cannot be instantiated:
        // Nogo1 ng1 = new Nogo1();
        // Nogo2 ng2 = new Nogo2();
        // But Nogo1() constructor called during instatiation of child:
        Go1 g1 = new Go1();
    }
}
class Go1 extends Nogo1
{
    Go1()
    {
        System.out.println("Go1()");
    }
}
abstract class Nogo1
{
    Nogo1()
    {
        System.out.println("Nogo1()");
    }
}
abstract class Nogo2
{

}

Output:

Thinking in Java Fourth Edition Bruce Eckel Chapter 8 Exercise 1

Exercise 1: Modify Exercise 9 in the previous chapter so that Rodent is an abstract class. Make the methods of Rodent abstract whenever possible

Solution:

package interfaces.rodent;

import java.util.*;

public class RandomRodentGenerator1 {
    private Random rand = new Random();

    public Rodent next() {
        switch (rand.nextInt(3)) {
        default:
        case 0:
            return new Mouse();
        case 1:
            return new Rat();
        case 2:
            return new Squirrel();
        }
    }
}
package interfaces.rodent;

abstract class Rodent {
    private String name = "Rodent";

    abstract protected void eat();

    abstract protected void run();

    abstract protected void sleep();

    abstract public String toString();
}

class Mouse extends Rodent {
    private String name = "Mouse";

    protected void eat() {
        System.out.println("Mouse.eat()");
    }

    protected void run() {
        System.out.println("Mouse.run()");
    }

    protected void sleep() {
        System.out.println("Mouse.sleep()");
    }

    public String toString() {
        return name;
    }
}

class Rat extends Rodent {
    private String name = "Rat";

    protected void eat() {
        System.out.println("Rat.eat()");
    }

    protected void run() {
        System.out.println("Rat.run()");
    }

    protected void sleep() {
        System.out.println("Rat.sleep()");
    }

    public String toString() {
        return name;
    }
}

class Squirrel extends Rodent {
    private String name = "Squirrel";

    protected void eat() {
        System.out.println("Squirrel.eat()");
    }

    protected void run() {
        System.out.println("Squirrel.run()");
    }

    protected void sleep() {
        System.out.println("Squirrel.sleep()");
    }

    public String toString() {
        return name;
    }
}

public class Rodent1 {
    private static RandomRodentGenerator1 gen = new RandomRodentGenerator1();

    public static void main(String[] args) {
        // Error: cannot instantiate abstract class:
        // Rodent x = new Rodent();
        // But OK to create array to be downcast to derived objects:
        Rodent[] rodents = new Rodent[10];
        for (Rodent r : rodents) {
            r = gen.next();
            System.out.println(r + ": ");
            r.eat();
            r.run();
            r.sleep();
        }
    }
}

Output:

Thinking in Java Fourth Edition Bruce Eckel Chapter 7 Exercise 17

Exercise 17: Using the Cycle hierarchy from Exercise 1, add a balance( ) method to Unicycle and Bicycle, but not to Tricycle. Create instances of all three types and upcast them to an array of Cycle. Try to call balance( ) on each element of the array and observe the results. Downcast and call balance( ) and observe what happens.

Solution:

package polymorphism.biking;

class Cycle {
    private String name = "Cycle";

    public static void travel(Cycle c) {
        System.out.println("Cycle.ride() " + c);
    }

    public String toString() {
        return this.name;
    }
}

class Unicycle extends Cycle {
    private String name = "Unicycle";

    public void balance() {
        System.out.println("Balance Unicycle");
    }

    public String toString() {
        return this.name;
    }
}

class Bicycle extends Cycle {
    private String name = "Bicycle";

    public void balance() {
        System.out.println("Balance Bicycle");
    }

    public String toString() {
        return this.name;
    }

}

class Tricycle extends Cycle {
    private String name = "Tricycle";

    public String toString() {
        return this.name;
    }
}

public class Biking17 {
    public static void main(String[] args) {
        Cycle[] ride = { new Unicycle(), new Bicycle(), new Tricycle(), };
        // Compile time error: cannot find balance() method in Cycle:
        // for(Cycle c : ride) {
        // c.balance();
        // }
        ((Unicycle) ride[0]).balance();
        ((Bicycle) ride[1]).balance();
        // Compile time error: no balance() in Tricycle:
        // ((Tricycle)ride[2]).balance();
        // RTTI: ClassCastException: Tricycle cannot be cast to Bicycle:
        // ((Bicycle)ride[2]).balance();
    }
}

Output:

Thinking in Java Fourth Edition Bruce Eckel Chapter 7 Exercise 16

Exercise 16: Following the example in Transmogrify.java, create a Starship class containing an AlertStatus reference that can indicate three different states. Include methods to change the states.

Solution:

class AlertStatus {
    public void alert() {
    }
}

class NormalAlert extends AlertStatus {
    public void alert() {
        System.out.println("AlertStatus Normal");
    }
}

class HighAlert extends AlertStatus {
    public void alert() {
        System.out.println("AlertStatus High");
    }
}

class MaximumAlert extends AlertStatus {
    public void alert() {
        System.out.println("AlertStatus Maximum");
    }
}

class Starship {
    private AlertStatus alertStatus = new NormalAlert();

    public void normalAlert() {
        alertStatus = new NormalAlert();
    }

    public void highAlert() {
        alertStatus = new HighAlert();
    }

    public void maximumAlert() {
        alertStatus = new MaximumAlert();
    }

    public void checkAlertStatus() {
        alertStatus.alert();
    }
}

public class Transmogrify16 {
    public static void main(String[] args) {
        Starship ss = new Starship();
        ss.checkAlertStatus();
        ss.highAlert();
        ss.checkAlertStatus();
        ss.maximumAlert();
        ss.checkAlertStatus();
        ss.normalAlert();
        ss.checkAlertStatus();
    }
}

Output:

Thinking in Java Fourth Edition Bruce Eckel Chapter 7 Exercise 15

Exercise 15: Add a RectangularGlyph to PolyConstructors.java and demonstrate the problem described in this section.

Solution:

class Glyph {
    void draw() {
        System.out.println("Glyph.draw()");
    }

    Glyph() {
        System.out.println("Glyph() before draw()");
        draw();
        System.out.println("Glyph() after draw()");
    }
}

class RoundGlyph extends Glyph {
    private int radius = 1;

    RoundGlyph(int r) {
        radius = r;
        System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
    }

    void draw() {
        System.out.println("RoundGlyph.draw(), radius = " + radius);
    }
}

class RectangularGlyph extends Glyph {
    private int length = 2;
    private int width = 4;

    RectangularGlyph(int l, int w) {
        length = l;
        width = w;
        System.out.println("RectangularGlyph.RectangularGlyph(), length = " + length + ", width = " + width);
    }

    void draw() {
        System.out.println("RectangularGlyph.draw(), length = " + length + ", width = " + width);
    }
}

public class PolyConstructors15 {
    public static void main(String[] args) {
        new RoundGlyph(5);
        new RectangularGlyph(3, 6);
    }
}

Output: