Wednesday, July 30, 2014

A shuffle method for array lists

It so happens that there is a method in Java specifically designed to shuffle array lists called, surprisingly, shuffle. Here is some code that enters items into an arrayList and then calls the shuffle method. the shuffle method is in the Collections library.

First here is my Item class that has one property "name."

package com.sponger.RandomizeArray;

public class Item {
 private String name;
 
 public Item(String name){
  setName(name);
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}

Now here is the Program class that creates an ArrayList of Items and then shuffles them

package com.sponger.RandomizeArray;

import java.util.ArrayList;
import java.util.Collections;

public class Program {

 public static void main(String[] args) {
  Program p = new Program();
  p.createArray();

 }
 
 private void createArray(){
  ArrayList<Item> myArray = new ArrayList<Item>();
  Item i = new Item("one");
  Item i2 =new Item("two");
  Item i3 =new Item("three");
  Item i4=new Item("four");
  Item i5=new Item("five");
  myArray.add(i);
  myArray.add(i2);
  myArray.add(i3);
  myArray.add(i4);
  myArray.add(i5);
  
  shuffle(myArray);
 }
 
 private void shuffle(ArrayList<Item> list){
  Collections.shuffle(list);
  
  for(Item i: list){
   System.out.println(i.getName());
  }
 }

}


After the shuffle it came out

four
two
five
one
three

Monday, July 28, 2014

Passing an object from one swing form to another

Here is the ListSelectionListener from my JListExample that gets the name from the list, requests the object associated with that list and then passes it to the second form.

private class SelectionListener implements ListSelectionListener{

@Override
public void valueChanged(ListSelectionEvent e) {
    
if (list.getSelectedIndex() != -1) {
   //No selection, disable fire button.
   String name=list.getSelectedValue();
            
   Item i = iList.getItem(name);
              
SecondForm second = new SecondForm(i);

   } 
       

   
}

Here is the code for the second form. Note especially the Constructor


package com.spconger.JListExample;

import java.awt.FlowLayout;
import java.awt.LayoutManager;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class SecondForm {
 Item i;
 
//the constructor takes in an object of the type Item
 public SecondForm(Item i){
  this.i=i;
  createJFrame();
 }
 
 private void createJFrame(){
  JFrame frame= new JFrame();
  frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
  frame.setBounds(200,200,200,200);
  frame.add(createPanel());
  frame.setVisible(true);
 }
 
 private JPanel createPanel(){
  JPanel panel = new JPanel();
  panel.setLayout(new FlowLayout(FlowLayout.LEFT));
//the labels get their value from the Item object passed in
  JLabel label1=new JLabel(i.getName());
  JLabel label2 = new JLabel(Double.toString(i.getPrice()));
  panel.add(label1);
  panel.add(label2);
  return panel;
 }

}

Saturday, July 26, 2014

Recipe Program Code and Diagrams.

I have posted the code for a version of the Recipe program on GitHub at https://github.com/spconger/RecipeProgram. If you want to work it out on its own, don't look at the code yet.

Here are some sequence diagrams that show how the objects communicate with each other in accomplishing certain tasks.



Thursday, July 24, 2014

Full Text Catalog

Here is the Full text stuff we did in class. I am still not sure why SQL server seems to be so allergic to the word "want."

--Full Text Catalog
use Master
Create Database FullTextDatabase
Go
--add a filegroup
Alter Database FullTextDatabase
Add Filegroup FullTextCatalog
go
use FullTextDatabase
go
--add a table with some text
Create Table TextTest
(
   TestId int identity (1,1) primary key,
   TestNotes Nvarchar(255)
)
go
--insert text
Insert into TextTest(TestNotes)
Values('For test to be successful we must have a lot of text'),
('The test was not successful. sad face'),
('there is more than one test that can try a man'),
('Success is a relative term'),
('It is a rare man that is always successful'),
('The root of satisfaction is sad'),
('men want success')
go
Select * From TextTest
go
--create full text catalog
Create FullText Catalog TestDescription
on Filegroup FullTextCatalog
go
--Create a full text index
Create FullText index on textTest(TestNotes)
Key Index [PK__TextTest__8CC33160448E9751]
on TestDescription
With Change_tracking auto
go
--run queries on the full text catalog

--find all instances that have the word "sad"
Select TestID, TestNotes 
From TextTest
Where FreeText(TestNotes, 'sad')

--do the same with successful
Select TestID, TestNotes 
From TextTest
Where FreeText(TestNotes, 'successful')

Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, '"success"')

Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, '"want"')

--look for any words containing the letters "success"
--the * is a wildcard
Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, '"success*"')

Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, '"want*"')

--looks for all grammatical forms of a word
Select TestID, TestNotes 
From TextTest
Where Contains(TestNotes, ' Formsof (Inflectional, Person)')

Wednesday, July 23, 2014

Relations between Classes

I am going to use examples from two projects, both on GitHub. The BookList example and the JListExample.

There are four basic types of relations between classes.

* Association
* Inheritance
* Aggregation
* Compositon

Association

Association is probably the most common relationship between classes. It exists when a class talks to another class by calling a method in that other class. In the JLIst example The Swing form has this relationship with ItemsList class. Association is shown with a simple line drawn between classes. Here is a diagram. (Note, I have only included the fields and methods that are immediately relevant.)

Here is the relevant code. The first is the constructor where the class is intitialized. The second from the private class of the action listener where the class is used to get a copy of the array list

public Mainform(){
  //Initialize the form and the ItemList 
  //in the constructor
  createFrame();
  iList = new ItemList();
 }

. . .

if (list.getSelectedIndex() != -1) {
            
//No selection, disable fire button.
              
 String name=list.getSelectedValue();
            
Item i = iList.getItem(name);

Inheritance

We have discussed inheritance. Inheritance is a parent/Child, general/specific kind of relationship. It it represented by a line with a triangle at one end. The triangle always points toward the parent in the relationship. You should also note that the relationship between a class that implements and interface and the interface is also represented as inheritance with the triangle always pointing toward the interface. Sometimes the line is dashed to distinguish it from regular inheritance.

Aggregation

Unlike Inheritance which represents a general/specific relationship, Aggregation represents a whole/part relationship.In the JListExample, the ItemList is the whole and the Items are the part. Aggregation assumes that the part can exist independently of the whole. Aggregation is represented by an empty diamond. The diamond always points to the whole.

Composition

Just like aggreagation, composition is a whole/part relationship. The only difference is that in composition the parts cannot exist independently from the whole. The ActionListener classes have this type of relation to the swing form. If the form is destroyed the listeners also go away. The line for composition has a filled in diamond. Again the diamond always points to the whole.

Sunday, July 20, 2014

Creating Report in SQL Server Data Tools 1

This is a tutorial for creating a simple report in SQL Server. We will use the database Automart and the view vw_LocationSummary.

First start the SQL Server data tools. Make sure you start it as administrator. You don't have to be Administrator to create the reports but you do to deploy them.

Start a new project and then chose Report Projects. We will name this report project "AutomartLocations."

In the solution explorer right click on the Shared Data Source folder.

In the dialog box that pops up change the name of the data source from DataSource1 to AutomartDataSource.

Click the Edit button. Key in Localhost for server and select the database Automart from the drop down list.

If you click on the credentials tab you will see that we are using Windows Authentication, though you can change it to Sql Server login or other credentials

Click OK.

Right click on Reports in the Solution window and choose Add New Report. This will start the report wizard.

Click Next

The next screen just confirms our data source. Click Next.

In the third string we need to build our query. Just type the following code into the query string box:,/p>

Select * from vw_LocationSummary

Click Next.

Choose Tabular for the report type.

Move all available fields into the details box

Click Next.

Choose the Report Style of your choice.

Click next.

The last screen is a summary. Change the name of the report to "Automart Locations" and check the box that says preview the report.

Click Finish.

The report opens on a preview.

There are couple of things to change. It would better if the total came after the Location name and count. It would also be nice to display the total as currency. Click the design tab.

If you click in the corner of the data field you will see a little icon representing a field list. We can use this to change the order of the fields. We will also,of course, need to change the column headings. this we do by simply typing over the existing column headings. I also increased the width of the first column by dragging the line in to the right.

To change the total to currency, right click on the text field for total and select text box totals.

Along the left side, choose number and then in the number dialog box choose currency.

Click OK and then preview the report again.

Deploying the Report

Before we can deploy the report we must specify where to deploy it. Click the Project menu and select AutomartLocation Properties. The target URL is blank. Change it to Localhost/ReportServer

Click OK. Now right click on the shared data source and click deploy. If you do nor deploy the data source first, you will not be able to deploy the report. Now right click on the report itself and click deploy. With luck you will get success.

Viewing the Reports in IE

We need to run Internet Explorer in Administrative mode to access and view our report. In Windows 8 this is not easy. You must Navigate to the executable file, right click on it, and choose run as administrator. It is found in C:\Program Files (x86)\Internet Explorer\iexplore.exe. When internet explorer launches write http://localhost/Reports in the address bar. It may take a few minutes to load the first time. Your should see something like in the image below. Your screen will look a little different because I have been doing other reports and practices.

Open the folder and view the report.

Thursday, July 17, 2014

Views for Reports

Use CommunityAssist
go
Create View vw_TotalDonationsByYearMonth
As
Select Year(DonationDate) [Year], 
Month(DonationDate) [Month],
Sum(DonationAmount) [Total Confirmed],
null as [Total Unconfirmed]
From Donation
Where DonationConfirmDate is not null
Group by Year(DonationDate), Month(donationDate)
Union 
Select Year(DonationDate) [Year], 
Month(DonationDate) [Month],
null as [Total Confirmed],
Sum(DonationAmount) [Total UnConfirmed]
From Donation
Where DonationConfirmDate is  null
Group by Year(DonationDate), Month(donationDate)
go


Select * from vw_TotalDonationsByYearMonth
Where [total confirmed] is not null
go
Create view vw_ServiceTotals
As
Select ServiceName, Coalesce (Sum(GrantAmount), 0) as Requested, 
Coalesce(Sum(GrantAllocation),0) as Granted,
Coalesce(Sum(GrantAmount)-Sum(GrantAllocation),0) as Difference
From CommunityService cs
Left Join ServiceGrant sg
on cs.ServiceKey=sg.ServiceKey
Group by ServiceName
Go

Create View vw_ServiceTotalsByYear
As
Select Year(GrantDate) as [Year],
ServiceName, Coalesce (Sum(GrantAmount), 0) as Requested, 
Coalesce(Sum(GrantAllocation),0) as Granted,
Coalesce(Sum(GrantAmount)-Sum(GrantAllocation),0) as Difference
From CommunityService cs
Inner Join ServiceGrant sg
on cs.ServiceKey=sg.ServiceKey
Group by Year(GrantDate),ServiceName
Go

Create view vw_GrantsTotalYearAndMonth
As
Select Year(GrantDate) [Year], Month(GrantDate) [Month],
Sum(GrantAmount) Requested, Coalesce(Sum(GrantAllocation),0) [Alloted]
From ServiceGrant
Group by Year(GrantDate), Month(GrantDate)
go

Create view vw_TopTenDonorsbyAmount
As
Select Top 10 PersonLastName, PersonFirstName, PersonUserName, 
Sum(DonationAmount) as Total
From Person p
Inner join Donation d
on p.PersonKey=d.PersonKey
Group by PersonLastName, PersonFirstName, PersonUserName
order by Total desc
Go

Create view vw_TopDonorsByCount
As
Select PersonLastName, PersonFirstName, PersonUserName, 
Count(DonationAmount) as Total
From Person p
Inner join Donation d
on p.PersonKey=d.PersonKey
Group by PersonLastName, PersonFirstName, PersonUserName
having Count(DonationAmount)>1

go
Create view vw_ResponseTimes
As
Select 
Avg(DateDiff(dd,GrantDate,GrantReviewDate) )as Average,
Max(DateDiff(dd,GrantDate,GrantReviewDate) ) as Most,
Min (DateDiff(dd,GrantDate,GrantReviewDate) ) as fewest
From ServiceGrant
Where DateDiff(dd,GrantDate,GrantReviewDate)>0
Go

Create View vw_EmployeeInfo
as
Select PersonLastName, PersonFirstName, PersonUserName,  EmployeeHireDate, 
EmployeeSSNumber, Coalesce(EmployeeDependents,0) as Dependents,  
EmployeeStatus, EmployeeMonthlySalary
From Person p
inner join employee e
on p.PersonKey=e.personkey

Wednesday, July 16, 2014

Code for Class 7/16/2014

I have published the code covering inheritance, abstract classes and interfaces on Github at https://github.com/spconger/BookLibrary

And here is the link to the multiple swing forms example https://github.com/spconger/MultipleSwingFormsExample

Tuesday, July 15, 2014

Automart Views for Reports


Use Automart
go
--this view returns the count of vehicles serviced and
--the count of unique vehicles serviced at each location
Create view vw_LocationServiceCount
As
Select LocationName [Location], Count(VehicleServiceId) as [Total Services],
Count (distinct VehicleId) as [Unique vehicles]
From customer.Location loc
Inner Join Employee.vehicleService vs
On loc.LocationID=vs.LocationID
Group by LocationName

Go
--creates a view that returns the 2 top best performing locations
--using top is one of the only times you are allowed
--to use order by in a view
Create view vw_TopLocationServiceCount
As
Select top 2 LocationName [Location], Count(VehicleServiceId) as [Total Services],
Count (distinct VehicleId) as [Unique vehicles]
From customer.Location loc
Inner Join Employee.vehicleService vs
On loc.LocationID=vs.LocationID
Group by LocationName
Order by Count(vehicleServiceId) desc


Go

--using the views. Location 

Select * From vw_TopLocationServiceCount 
Select * From vw_LocationServiceCount 

Select top 5 * from Employee.VehicleService order by ServiceDate desc




Go
--this function calculates the amount with discount
--charged for a particular service
Create function fx_GetTotalDue
 (@price money, @discount decimal(3,2))
 returns money
 As
 Begin
 declare @amount money
 
 Set @amount=@Price - @price* @discount;
 

return @amount
 end
 Go
 --this function calculates the tax due on a service
 Create Function fx_CalculateTax
 (@price money, @TaxPercent decimal(3,2))
 returns money
 as
 begin
 return @Price * @taxPercent
 end
 go

 --this query uses the GetTotal due function
 Select ServiceName,ServicePrice, DiscountPercent, dbo.fx_GetTotalDue(ServicePrice, DiscountPercent) as total
 From Customer.AutoService a
 inner join Employee.VehicleServiceDetail vsd
 on a.AutoServiceID=vsd.AutoServiceID
 go

 --this view presents a summary of  totals for each location
 Create View vw_LocationSummary
 As
 Select LocationName, count(distinct vs.VehicleServiceId) as [Count],
 sum(dbo.fx_GetTotalDue(ServicePrice, DiscountPercent)) as Total
 From Customer.AutoService a
 inner join Employee.VehicleServiceDetail vsd
 on a.AutoServiceID=vsd.AutoServiceID
 inner Join Employee.VehicleService vs
 on vsd.VehicleServiceID=vs.VehicleServiceID
 inner Join Customer.Location loc
 on loc.LocationID=vs.LocationID
 Group by LocationName

 go

 --this view provides a summary of all 
 --customer services and charges
 --It would need to be used with a where
 --clause
 Create view vw_CustomerSummary
 As
 Select LastName, Firstname,
 LicenseNumber,VehicleMake, VehicleYear,
 ServiceDate, LocationName,
 ServiceName, ServicePrice, DiscountPercent, 
 dbo.fx_GettotalDue(ServicePrice, DiscountPercent) as SubTotal,
 dbo.fx_CalculateTax(ServicePrice, TaxPercent) as Tax,
 dbo.fx_GettotalDue(ServicePrice, DiscountPercent) 
 + dbo.fx_CalculateTax(ServicePrice, TaxPercent) as Total
 from Person p
 inner Join Customer.Vehicle v
 on p.Personkey=v.PersonKey
 inner join Employee.VehicleService vs
 on v.VehicleId =vs.VehicleID
 inner join Employee.VehicleServiceDetail vsd
 on vs.VehicleServiceID=vsd.VehicleServiceID
 inner join Customer.AutoService a
 on a.AutoServiceID =vsd.AutoServiceID
 inner join Customer.Location loc
 on loc.LocationID=vs.LocationID

 Go

 --using the customer view

 select * from vw_CustomerSummary where LicenseNumber='ITC226'
 Select sum(Subtotal) [subtotal], sum(Tax) [Tax],sum(Total)[Total]
 From vw_CustomerSummary
 Where licenseNumber='ITC226'

Wednesday, July 9, 2014

FirstSwingExample in-class

Here is the ExampleForm.Java

package com.spconger.SwingExample;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


public class ExampleForm {
 
 //declare the form objects
 private JFrame frame;
 private JPanel panel;
 private JLabel lblNumber;
 private JTextField txtNumber;
 private JButton btnSubmit;
 private JLabel lblPrime;
 
 private final int OFFSETX=200;
 private final int OFFSETY=300;
 private final int X=420;
 private final int Y=150;
 
 public ExampleForm(){
  createFrame();
 }
 
 private void createFrame(){
  frame = new JFrame();
  frame.add(createPanel());
  frame.setTitle("Prime Number Calculator");
  frame.setBounds(OFFSETX,OFFSETY,X,Y);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }
 
 private JPanel createPanel(){
  panel = new JPanel();
  panel.setLayout(new GridLayout(2,2,5,5));
  
  lblNumber=new JLabel("Enter an integer between 1 and 41");
  txtNumber=new JTextField();
  btnSubmit=new JButton("Get Prime");
  btnSubmit.addActionListener(new SubmitListener());
  lblPrime = new JLabel();
  
  panel.add(lblNumber);
  panel.add(txtNumber);
  panel.add(btnSubmit);
  panel.add(lblPrime);
  
  return panel;
 }
 
 private class SubmitListener implements ActionListener{

  @Override
  public void actionPerformed(ActionEvent arg0) {
   try{
    int number = Integer.parseInt(txtNumber.getText());
    if(number > 0 && number < 42){
     int prime = number * number - number + 41;
     lblPrime.setText(Integer.toString(prime));
    }//end if
    else{
     JOptionPane.showMessageDialog
                 (null,"Enter an integer between 1 and 41", "Invalid Number",0);
     txtNumber.setText("");
     txtNumber.grabFocus();
    
    }//end else
   
   }//end try
   catch(NumberFormatException e){
    JOptionPane.showMessageDialog
                 (null,"Not a valid number", "Invalid Number",0);
    txtNumber.setText("");
    txtNumber.grabFocus();
   }//end catch
   
  }
  
 }

}

Here is the Program.java

package com.spconger.SwingExample;

public class Program {

 public static void main(String[] args) {
  ExampleForm ex = new ExampleForm();

 }

}

Here is a picture of the form after pressing the button

Monday, July 7, 2014

A java class example

Here is a class that calculates a simplified weekly payroll. Notice components that make up the class:

Fields: Fields are class level variables that describe the object. In this case we need the employee number, the rate of pay and the number of hours worked for the week.

Constants: Constants are values that cannot be changed in the course of the program. Java uses the word "final" to designate a constant. The naming convention for constants is to use all caps.

Sets and Gets: fields should be private. This is part of an object oriented principle called Encapsulation. You can use sets and gets to expose these private fields to outside classes. Sets allow another class to change the value of the underlying field. Gets allow another class to see the current value of a field. Not every field needs to be seen by other classes. You can also make a set without a get or visa-versa. You can also add validation to the sets if needed.

Public Methods: public methods are methods that can be accessed by other classes. You can also make private methods for things that are only internal to the class. Notice that each method does one thing. That makes troubleshooting and maintenance much easier.

Constructors: constructors are specialized methods whose purpose is to initialize or "construct" the class. Constructors can be overridden. This call has three constructors: an empty constructor that takes no parameters, a constructor that takes just the employee's number and a constructor that takes the employee number, the pay rate and the hours worked. You can have as many constructors as you want as long as each constructor has a different set of parameters. (It is important to note it is not the name of the parameter that matters, but the data type. You can only have one constructor that takes a single String parameter, even if they represent different Strings. So you can't do something like


public Pay(String employeeNumber){}
public Pay(String employeeName){}

They would not be seen as different by the complier.) Only one constructor is used for any instance of the class. Which constructor is used is determined by the parameters that are passed. In our example I used the last constructor that takes the employee number, pay rate and hours.

Here is the Pay.java class


package com.spconger.PayrollExample;

public class Pay {
 /*
  * This class represents a simplified
  * Payroll class. It calculates base pay,
  * overtime pay. total pay and net pay
  * with deductions for social security
  * federal withholding and union dues
  * it has a ToString method that returns
  * a complete pay stub
  * Steve Conger, 7/7/1014
  */
 //fields: class level variables that describe the object
 private String employeeNumber;
 private double payRate;
 private double hoursWorked;
 
 //declare a constant
 private final double UNIONDUES=.02;
 
 //get and set methods to allow access
 //to each field
 
 public String getEmployeeNumber() {
  return employeeNumber;
 }
 public void setEmployeeNumber(String employeeNumber) {
  this.employeeNumber = employeeNumber;
 }
 public double getPayRate() {
  return payRate;
 }
 public void setPayRate(double payRate) {
  this.payRate = payRate;
 }
 public double getHoursWorked() {
  return hoursWorked;
 }
 public void setHoursWorked(double hoursWorked) {
  this.hoursWorked = hoursWorked;
 }

 
 
 //public methods
 
 public double calculateBasePay(){
  double basePay = getHoursWorked() * getPayRate();
  return basePay;
 }
 
 public double calculateOvertimePay(){
  double overtime=(getHoursWorked()-40) * getPayRate()*1.5;
  return overtime;
 }
 
 public double calculateTotalPay(){
  return calculateBasePay() + calculateOvertimePay();
 }

 public double calculateSocialSecurity(){
  double ss=0;
  double ssPercent=0;
  
  double total = calculateTotalPay();
  if(total > 1500)
   ssPercent=.25;
  else if (total > 1000)
   ssPercent=.2;
  else if (total > 600)
   ssPercent=.15;
  else 
   ssPercent=.1;
  
   
  ss=total * ssPercent; 
    
  return ss;
 }
 
 public double calculateFederalWithholding(){
  double fw=0;
  double fwPercent=0;
  
  double total = calculateTotalPay();
  if(total > 1500)
   fwPercent=.1;
  else if (total > 1000)
   fwPercent=.08;
  else if (total > 600)
   fwPercent=.05;
  else 
   fwPercent=.01;
  
  fw=total * fwPercent;
  
  return fw;
 }
 
 public double calculateUnionDues(){
  return calculateTotalPay()*UNIONDUES;
 }
 
 public double calculateTotalDeductions(){
  return calculateSocialSecurity() + calculateFederalWithholding() 
    + calculateUnionDues();
 }
 
 public double calculateNetPay(){
  return calculateTotalPay()-calculateTotalDeductions();
 }
 
 
 public String toString(){
  
  String paystub= "Employee Number: "
    + getEmployeeNumber() 
    + "\n"
    + "Hours: "
    + getHoursWorked() 
    + "\n"
    + " Rate: "
    + getPayRate()
    + "\n"
    + " Base Pay: "
    + calculateBasePay()
    + "\n"
    + " Overtime: "
    + calculateOvertimePay()
    + "\n"
    + "Total Pay: " 
    + calculateTotalPay()
    + "\n"
    + "Social Security Detuction: "
    + calculateSocialSecurity()
    + "\n"
    + "Federal Witholding: "
    + calculateFederalWithholding()
    + "\n"
    + "Union dues: "
    + calculateUnionDues()
    + "\n"
    + "Total Deductions: "
    + calculateTotalDeductions()
    + "\n"
    + "Net Pay: "
    + calculateNetPay();
  
  return paystub;
  
    
 }
 //public constructors
 //empty Constructor
 public Pay(){
  
 }
 
 //Overridden constructor that takes employee number
 public Pay(String emp){
  setEmployeeNumber(emp);
 }
 
 //overridden constructor
 public Pay(String emp, double rate, double hours){
  setEmployeeNumber(emp);
  setPayRate(rate);
  setHoursWorked(hours);
 }

}


Here is Program.java


package com.spconger.PayrollExample;

public class Program {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Program p=new Program();
  p.Display();

 }
 
 private void Display(){
  Pay pay = new Pay("345", 35.75, 45);
  System.out.println(pay.toString());
 }

}


Here is a picture of the results using the toString() method.

Thursday, July 3, 2014

FIrst Java Examples

Here is the code for the first two days:

First Java

package com.spconger.FirstJava;

import java.util.Scanner;

public class Program {
 /*
  * This class takes a word and a number
  * as arguments 
  * and outputs the word as many times as 
  * the number indicates
  * Steve Conger 6/30/2014
  */

 public static void main(String[] args) {
  //initialize the program class
  Program p = new Program();
  p.getInput();

 }
 
 private void getInput(){
  Scanner scan = new Scanner(System.in);
  String name=null;
  int number;
  System.out.println("Please enter a name or something");
  name=scan.next();
 
 
  
  if(name != null)
  {
   System.out.println("Enter how many time you want it to repeat");
   number=scan.nextInt();
   
   display(name, number);
   
  }
  
  else
  {
  
  System.out.println("You must enter a word");
  }
 }
 
 private void display(String name, int number){
  for (int i = 0; i < number; i++){
   System.out.println(name);
  }
 }

}


Array Example

package com.spconger.ArrayExample;

import java.util.Random;
import java.util.Scanner;

public class Program {
 int[] myArray = new int[10];
 
 public static void main(String[] args) {
  Program p = new Program();
  //p.createArray();
  //p.displayArray();
  p.twoDimensionalArray();
 }
 
 private void createArray()
 {
  
  
  Random rand = new Random();
  
  for (int i=0;i<myArray.length;i++){
   myArray[i]=rand.nextInt(300);
  }
 }
 
 private void displayArray(){
  for(int i=0;i<myArray.length;i++){
   System.out.println(myArray[i]);
  }
 }
 
 private void twoDimensionalArray(){
  String[] [] classes = new String[4][2];
  classes[0][0]="ITC115";
  classes[0][1]="Conger";
  classes[1][0]="ITC 240";
  classes[1][1]="Newman";
  classes[2][0]="NET 120";
  classes[2][1]="Messerly";
  classes[3][0]="ITC 224";
  classes[3][1]="Conger";
  
  System.out.println("Enter an instructor's name");
  Scanner scan = new Scanner(System.in);
  String instructor=scan.next();
  
  for(int i=0;i<classes.length;i++){
   if(classes[i][1].equals(instructor)){
    System.out.println(classes[i][0]);
   }
  }
 }
 

}


While Loop Example

package com.spconger.WhileLoopExample;

import java.util.Scanner;

public class Program {

 public static void main(String[] args) {
  Program p = new Program();
  //p.whileLoop();
  p.forEachLoop();

 }
 
 private void whileLoop(){
  String answer="Yes";
  int counter=0;
  Scanner scan = new Scanner(System.in);
  while (answer.equals("Yes") || answer.equals("yes")){
   counter ++;
   System.out.println(counter);
   System.out.println("Would you like to continue? Yes/No");
   
   answer = scan.next();
   
  }
  
  
 }
 private void DoWhileLoop()
 {
   String answer = "no";
   int counter=0;
   Scanner scan = new Scanner(System.in);
   do
   {
    counter++;
    System.out.println(counter);
    System.out.println("Would you like to continue? Yes/No");
   }while(answer.equals("Yes")|| answer.equals("yes"));
 }
 
 private void forEachLoop(){
  String[] colors = new String[] {"Red", "Green", "Blue", "Orange","Purple"};
  for(String s: colors){
   System.out.println(s);
  }
 }

}