Monday, October 31, 2011

Java Equivalent to ITC110 Assignment 5

Here is the java code


import java.util.Scanner;
public class GuessingGame {

 /**
  * This program presents a guessing game
  * where the computer randomly selects
  * a number between 0 and 1000
  * and the player gets 10 chances to guess
  * the player can play as many times
  * as he or she wants and the program
  * will list total wins and average score
  */
 int gameCounter=0;
 int[] scoreArray=new int[50];
 public static void main(String[] args) {
  //instantiate the class
  GuessingGame gg = new GuessingGame();
  //get the scanner
  Scanner reader = new Scanner(System.in);
  //initialize the variable for exiting
  int choice=1;
  //loop so the player can play until they choose
  //to quit
  do
  {
   //call the start of the game
  gg.Start();
  //increment the number of games
  gg.gameCounter++;
  System.out.println("Do you want to play again? 0 to quit");
  choice=reader.nextInt();
  
  }while (choice != 0);

 }
 
 private void Start()
 {
  //Call the method to get the random number
  double num=GetRandom();
  //the line below just for testing 
  //System.out.println((int)num);
  
  //cast the random number to an integer
  //and pass to the GetGuess method
  GetGuess((int)num);
 }
 
 private double GetRandom()
 {
  //Get the random number
  double number = Math.random()*1000;
  return number;
 }
 
 private void GetGuess(int number)
 {
  int score; //declare score counter
  Scanner reader = new Scanner(System.in);
  //loop backwards to keep score
  for(score=10; score > 0; score--)
  {
   System.out.println("Enter a quess between 0 and 1000");
   double guess=reader.nextDouble();
   
   //check the guesses
   if(guess > number)
    System.out.println("Your guess is too high");
   else if(guess < number)
    System.out.println("Your guess is too low");
   else
   {
    System.out.println("congratulations");
    break; //leave the loop if correct
   }
  }
  GetScores(score);//call the get scores method
 }
 
 private void GetScores(int score)
 {
  //output the current score
  System.out.println("Your current Score is " + score);
  //assign it to the scoreArray
  scoreArray[gameCounter]=score;
  //initialize the variable to get the totals
  int scoreTotal=0;
  //loop through the array to get the total

  for (int i=0;i<50;i++)
  {
   scoreTotal+=scoreArray[i];
  }
  //get the average casting it to a double to get decimal
  //pars
  double scoreAverage=(double)scoreTotal/(double)(gameCounter + 1);
  //pring out the results
  System.out.println("Your have played " + (gameCounter + 1) + "games");
  System.out.println("Your average score is " + scoreAverage);
 }

}

Here is a transcript of the console when the program is running


Enter a quess between 0 and 1000
500
Your guess is too low
Enter a quess between 0 and 1000
750
Your guess is too low
Enter a quess between 0 and 1000
875
Your guess is too high
Enter a quess between 0 and 1000
800
Your guess is too low
Enter a quess between 0 and 1000
850
Your guess is too high
Enter a quess between 0 and 1000
825
Your guess is too high
Enter a quess between 0 and 1000
812
Your guess is too low
Enter a quess between 0 and 1000
819
Your guess is too low
Enter a quess between 0 and 1000
822
Your guess is too low
Enter a quess between 0 and 1000

823
congratulations
Your current Score is 1
Your have played 1games
Your average score is 1.0
Do you want to play again? 0 to quit
1
Enter a quess between 0 and 1000
500
Your guess is too high
Enter a quess between 0 and 1000
250
Your guess is too low
Enter a quess between 0 and 1000
350
Your guess is too low
Enter a quess between 0 and 1000
425
Your guess is too low
Enter a quess between 0 and 1000
475
Your guess is too high
Enter a quess between 0 and 1000
450
Your guess is too high
Enter a quess between 0 and 1000
433
Your guess is too low
Enter a quess between 0 and 1000
444
Your guess is too high
Enter a quess between 0 and 1000
439
Your guess is too low
Enter a quess between 0 and 1000
441
Your guess is too high
Your current Score is 0
Your have played 2games
Your average score is 0.5
Do you want to play again? 0 to quit

0

Thursday, October 27, 2011

MultiDimensional Arrays

The simplest multidimensional array is a two dimensional array. You can think of a two dimensional array as a simple sort of table with columns and rows. The first dimension is the number of rows and the second dimension is the number of columns.

Here is an example of a two dimensional string array that keeps track of book titles and authors. It has 3 rows and 2 columns


 string[,] books = new string[3, 2];
           
            books[0, 0] = "War and Peace";
            books[0, 1] = "Tolstoy";
            books[1, 0] = "Lord of the Rings";
            books[1, 1] = "Tolkein";
            books[2, 0] = "Huckleberry Finn";
            books[2, 1] = "Twain";

Here is an example of a two dimensional array with 3 rows and 3 columns. Think of it as containing the height, width and length of a set of boxes

int[,] boxes = new int[3, 3];
            boxes[0, 0] = 4;
            boxes[0, 1] = 2;
            boxes[0, 2] = 3;
            boxes[1, 0] = 2;
            boxes[1, 1] = 2;
            boxes[1, 2] = 1;
            boxes[2, 0] = 3;
            boxes[2, 1] = 2;
            boxes[2, 2] = 5;

It is also possible to have arrays with more than two dimensions. Below is a three dimensional array.

int[, ,] space = new int[2, 2, 2];

            space[0, 0, 0] = 5;
            space[0, 0, 1] = 4;
            space[0, 1, 0] = 3;
            space[0, 1, 1] = 4;
            space[1, 0, 0] = 3;
            space[1, 0, 1] = 6;
            space[1, 1, 0] = 2;
            space[1, 1, 1] = 5;
            space[2, 0, 0] = 3;
            space[2, 0, 1] = 6;
            space[2, 1, 0] = 2;
            space[2, 1, 1] = 5;

Arrays can have more than 3 dimensions, but they rapidly get difficult to manage.

To display a multidimensional array, you access its indexes just as in an one dimensional array. Below is the full program that creates these arrays and displays all but the last one. If you would like a little chalange, you can add code to the display method to display the contents of the 3 dimensional array.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MultidimensionalArrays
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            p.Display();
            Console.ReadKey();
        }

        private string[,] TwoDimensionalArray()
        {
            //define two dimensional Array
            //first number is number of rows
            //the second is number of columns
            string[,] books = new string[3, 2];
           
            books[0, 0] = "War and Peace";
            books[0, 1] = "Tolstoy";
            books[1, 0] = "Lord of the Rings";
            books[1, 1] = "Tolkein";
            books[2, 0] = "Huckleberry Finb";
            books[2, 1] = "Twain";

            return books;
        }

        private int[,] Another2DimensionalArray()
        {
            //think of an array that holds
            //the height, width, and length
            //of boxes
            //although it has 3 columns
            //it is still a two dimensional 
            //array
            int[,] boxes = new int[3, 3];
            boxes[0, 0] = 4;
            boxes[0, 1] = 2;
            boxes[0, 2] = 3;
            boxes[1, 0] = 2;
            boxes[1, 1] = 2;
            boxes[1, 2] = 1;
            boxes[2, 0] = 3;
            boxes[2, 1] = 2;
            boxes[2, 2] = 5;

            return boxes;

        }

        private int[, ,] ThreeDimensionalArray()
        {
            //think of 3 dimensionals as a cube
            //you can do more dimensions but it
            //gets beyond absurd
            int[, ,] space = new int[2, 2, 2];

            space[0, 0, 0] = 5;
            space[0, 0, 1] = 4;
            space[0, 1, 0] = 3;
            space[0, 1, 1] = 4;
            space[1, 0, 0] = 3;
            space[1, 0, 1] = 6;
            space[1, 1, 0] = 2;
            space[1, 1, 1] = 5;
            space[2, 0, 0] = 3;
            space[2, 0, 1] = 6;
            space[2, 1, 0] = 2;
            space[2, 1, 1] = 5;

            return space;
        }

        private void Display()
        {
            //you access the values in multidimensional arrays
            //just like regular ones, through their indexes

            string[,] mybooks = TwoDimensionalArray();
            Console.WriteLine("The second book is {0}, by {1}", 
                mybooks[1, 0], mybooks[1, 1]);
            Console.WriteLine("*********************************");
            // the loop below multiplies the contents
            //of the three columns together
            int[,] cubes = Another2DimensionalArray();
            int cubicInches = 0;
            for (int i = 0; i < 3; i++)
            {
                cubicInches = cubes[i, 0] * cubes[i, 1] * cubes[i, 2];
                Console.WriteLine("Box {0}, is {1} cubic inches", i+1, cubicInches);
            }
            Console.WriteLine("*********************************");
           
        }
    }
}

Wednesday, October 26, 2011

Midterm code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExamExample
{
    class Program
    {
        const int SIZE = 50;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.CreateArrays();
            p.PauseIt();
        }

       

        private void CreateArrays()
        { 
            int[] numbers= new int[SIZE];
            FillArray(numbers);

        }

        private void FillArray(int[] numbers)
        {
            Random rand = new Random();
            for (int i = 0; i < SIZE; i++)
            {
                numbers[i] = rand.Next(1, 100);
            }
            GetEvenNumbers(numbers);
        }

        private void GetEvenNumbers(int[] numbers)
        {
            int evenCount = 0;
            int oddCount = 0;

            for (int i = 0; i < SIZE; i++)
            {
                if (numbers[i] % 2 == 0)
                {
                    evenCount++;
                }
                else
                {
                    oddCount++;
                }

            }
            Console.WriteLine("There were {0} even numbers and {1} odd numbers", evenCount, oddCount);
           
        }

        private void PauseIt()
        {
            Console.WriteLine("\n\nPress any key to exit");
            Console.ReadKey();
        }

       
    }
}


Tuesday, October 25, 2011

Random

Here is the random Function

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RandomExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int number=rand.Next(1, 1000);

            Console.WriteLine(number);

            Console.ReadKey();
        }
    }
}

Assignment4 Morning Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Assignment4Morning
{
    class Program
    {
        /// 
        /// This program calculates GPAs
        /// Based on grades and credits
        /// entered
        /// Steve Conger 10/25/2011
        /// 
      
        static void Main(string[] args)
        {
            Program p = new Program();

            string quit = "y";
            while (quit != "n")
            {
                p.CreateGPAArrays();
                Console.WriteLine("Continue y/n?");
                quit = Console.ReadLine();
               quit= quit.ToLower();
            }
            //Console.ReadKey();
        }//end main

        private void CreateGPAArrays()
        {
            Console.WriteLine("Enter how many grades you want to enter");
            int number = int.Parse(Console.ReadLine());

            double[] grades = new double[number];
            int[] credits = new int[number];

            FillGPAArrays(grades, credits);
        }//end Create

        private void FillGPAArrays(double[] grades, int[] credits)
        {
            for (int index = 0; index < grades.Length; index++)
            {
                double grade=0;
                
                do
                {
                    Console.WriteLine("enter grade");
                    grade = double.Parse(Console.ReadLine());
                    if (grade < 0 || grade > 4)
                    {
                        Console.WriteLine("Grades must be between 0 and 4");
                        
                    }
                } while (grade < 0 || grade > 4);
                grades[index] = grade;

                Console.WriteLine("enter Credits");
                credits[index] = int.Parse(Console.ReadLine());

            
            }//end for
            CalculateGPA(grades, credits);
        }//end Fill

        private void CalculateGPA(double[] grades, int[] credits)
        {
            double weight=0;
            int totalCredits = 0;

            for (int index = 0; index < grades.Length; index++)
            {
                weight += grades[index] * credits[index];
                totalCredits += credits[index];
            }

            //alternate way to sum credits
            //c# 4.0 and above only
            int total = credits.Sum();

            double gpa = weight / totalCredits;

            Console.WriteLine("Your GPA is {0}", Math.Round(gpa,1));
            
        }


    }//end class
}

Monday, October 24, 2011

Assignment 4


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Assignment4
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            string quit = "y";
            while (quit != "n")
            {
                p.CreateArrays();
                Console.WriteLine("Do you want start over? n to quit");
               quit=Console.ReadLine();
                quit.ToLower();
            }
            Console.ReadKey();
        }

        private void CreateArrays()
        {
            Console.WriteLine("How many Grades do you want to enter");
            int number = int.Parse(Console.ReadLine());

            double[] grades = new double[number];
            double[] credits = new double[number];

            FillArrays(grades, credits);
            

        }

        private void FillArrays(double[] grades, double[] credits)
        {
            for (int counter = 0; counter < grades.Length; counter++)
            {
                double grade = 0;
                do
                {
                    Console.WriteLine("Enter a Grade");
                    grade = double.Parse(Console.ReadLine());
                    if (grade <= 0 || grade > 4)
                    {
                        Console.WriteLine("Grades must be between 0 and 4");
                    }

                } while (grade <= 0 || grade > 4);
                grades[counter]=grade;

                Console.WriteLine("Enter the Credits");
                credits[counter] = double.Parse(Console.ReadLine());
            }//end for
            CalculateGPA(grades, credits);
        }//end fill arrays

        private void CalculateGPA(double[] grades, double[] credits)
        {
            double totalCredits = 0;
            double weight = 0;

            for (int counter = 0; counter < grades.Length; counter++)
            {
                weight+=grades[counter] * credits[counter];
                totalCredits += credits[counter];
            }//end for

            
            
            double gpa = weight / totalCredits;

            Console.WriteLine("Your GPA is {0:F1}", gpa);
        }

    }//end class
}

and here is the code for doing random numbers


 static void Main(string[] args)
  {
            
            Random rand = new Random();
            int number = rand.Next(1, 10);
            Console.WriteLine(number);
            Console.ReadKey();

   }

Thursday, October 20, 2011

Java Equivalent of ITC110 Assignment 4

This is an assignment that deals with loops and arrays. It uses two array one for Grades and one for Credits. The purpose of the program is to calculate a GPA. The arrays are created in one method and then passed to another where they are filled in a for loop. Then they are passed to a third method where the arrays are multiplied together and summed to get the GPA.

Two other loops are added. One, a while loop in main, lets the user repeat the program as often as they wish. They enter 0 to exit. The other, a do loop, is used in the FillArrays method to make sure the grade is between 0 and 4. It will not allow the user to continue until they have entered a grade in the valid range. The grade is not written to the array until it is valid.

Here is the Java code


import java.util.Scanner;

public class GPACalculator {

 /**
  * This program calculates a GPA 
  * to do so it uses parallel arrays
  * one for grades and one for credits
  * it checks to make sure grades are
  * between 0 and 4
  * this program is the java equivalent
  * of ITC110 assignment 4
  * Steve Conger !0/20/2011
  */
 //declare the scanner globally
 Scanner reader = new Scanner(System.in);
 
 public static void main(String[] args) {
  GPACalculator calc=new GPACalculator();
  int choice=1;
  while(choice !=0)
  {
   calc.CreateArrays();
   System.out.println("Do you want to enter more grades: 0 to exit");
   choice=calc.reader.nextInt();
  }
  
 }
 
 private void CreateArrays()
 {
  
  System.out.println("How many grades do you want to enter?");
  int number=reader.nextInt();
  
  //declare the arrays
  double[] grades = new double[number];
  double[] credits=new double[number];
  
  //call the FillArrays method
  FillArrays(grades, credits);
 }
 
 private void FillArrays(double[] grades, double[]credits)
 {
  //loop through and fill the arrays)
  for(int i=0;i<grades.length; i ++)
  {
   //the do loop makes sure the grade is in 
   //the proper range
   double grade=0;
   do
   {
   System.out.println("Enter the grade");
   grade=reader.nextDouble();
   if(grade<0 || grade>4)
   {
    System.out.println("Grades must be between 0 and 4");
   }
   }while (grade<0 || grade>4);
   grades[i]=grade;
   System.out.println("Enter the credits");
   credits[i]=reader.nextDouble();
  }
  //call the CalculateGPA method
  CalculateGPA(grades, credits);
 }
 
 private void CalculateGPA(double[] grades, double[]credits)
 {
  double weight=0;
  double totalCredits=0;
  
  for(int i=0;i<grades.length; i ++)
  {
   weight += grades[i] * credits[i];
   totalCredits += credits[i];
  }
  
  double gpa = weight / totalCredits;
  System.out.println("Your GPA is " + gpa);
  
 }
 

}

Wednesday, October 19, 2011

Consuming a Simple Web Services

This blog leads you through the process of consuming a simple web service. In it we will find a web service that provides global weather reports based on city and country and we will reference that web service in our own ASP.Net form and create our own little app that uses it.

Go to this url to get Free web services: http://www.webservicex.net/WS/wscatlist.aspx

Click on global weather

Click on get weather

Copy WSDL Schema Location http://www.webservicex.net/globalweather.asmx?WSDL

Open Visual Studio

Create a new website

Go to the Website menu, And select add web reference

Paste the schema location in the URL text box

Change the name of the web service name to net.globalweather.www

Add the web service add a labels and textboxes for city name and country and a button and a label to the web form



<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Global Weather</h1>
      <p> 
         <asp:Label ID="Label2" runat="server" Text="Enter City"> 
        </asp:Label><asp:TextBox ID="txtCity" runat="server"></asp:TextBox> 
      </p>
      <p>
        <asp:Label ID="Label3" runat="server" Text="Enter Country">
        </asp:Label><asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
      </p>
      <p>
        <asp:Button ID="Button1" runat="server" Text="Get Weather" />
       </p>
       <p>
        <asp:Label ID="lblWeather" runat="server" Text="Label"></asp:Label>
        </p>
    </div>
    </form>
</body>
</html>

Double click the buttom in design mode to get to the C# code window

In the buttonI_click method enter the following code

 protected void Button1_Click(object sender, EventArgs e)
 {
     GlobalWeather gw = new GlobalWeather();
     string weather = gw.GetWeather(txtCity.Text, txtCountry.Text);
     lblWeather.Text = weather;
 }

Note how little code it takes to process this. The web service tells you when you add it that this method requires two string arguments (city and country) and that it returns a string. Some webservices can be more complex, but most are fairly straight forward to use

Here is a picture of the form running

Tuesday, October 18, 2011

Java Equivalent to C# Assignment 3


package Income;
import java.util.Scanner;

public class NetIncomeCalculator {

 /**
  * This program calculates gross pay
  * and net pay given deductions in 
  * Social Security, medicare and a bus
  * pass. It uses else if statments
  * to determine the rate of deduductions
  * This is the equivalent of
  * Assignment three in C# in ITC 110
  * Steve Conger 10/18/2011
  */
 
 //declaring constants
 //final double SOCIALSECURITY = .09;
 //final double MEDICARE=.03;
 final int BUSPASS=25;
   
 public static void main(String[] args) {
  //declare and instantiate the class
  //to load it (main being static is
  //already loaded into memory
  NetIncomeCalculator netcalc = new NetIncomeCalculator();
  //call the starting method
  netcalc.Display();
 }
 
 private void Display()
 {
  //get input
  //the scanner is an object to read from the console
  Scanner reader = new Scanner(System.in);
  System.out.println("Enter the number of hours worked");
  double hours = reader.nextDouble();
  System.out.println("Enter your rate per hour");
  double rate=reader.nextDouble();
  
  //call the methods to do the calculations
  double grossPay=CalcIncome(hours, rate);
  double socialSec = CalcSocialSecurity(grossPay);
  double medicare = CalcMedicare(grossPay);
  double netPay=CalcNetPay(grossPay, socialSec, medicare);
  
  //outputs
  System.out.println("Your gross income is " + grossPay);
  System.out.println("Your Social Security deduction is " + socialSec);
  System.out.println("Your Medicare deduction is " + medicare);
  System.out.println("Your Bus pass deduction is " + BUSPASS/4);
  System.out.println("Your net pay is " + netPay);
 }
 
 private double CalcIncome(double hrs, double rt)
 {
  double gross=0;
  //check to see if the hours are more than forty
  //if they are pay time and a half for overtime
  //if not just pay the rate of pay
  if (hrs > 40)
  {
   gross=rt * (40 + ((hrs-40)*1.5));
  }
  else
  {
   gross = rt * hrs;
  }
  return gross;
 }
 
 private double CalcSocialSecurity(double gPay)
 {
  double ss =0;
  if (gPay >= 5000)
   ss=.4;
  else if (gPay >= 4000 )
   ss=.35;
  else if (gPay >=3000)
   ss=.25;
  else if (gPay >=2000)
   ss=.2;
  else if (gPay > 1000)
   ss=.12;
  else
   ss=.09;
  
  return gPay * ss;
 }
 
 private double CalcMedicare(double gPay)
 {
  double med=0;
  if (gPay >=5000)
   med=.2;
  else if (gPay >= 2000)
   med=.1;
  else
   med=.05;
  return gPay * med;
 }
 
 private double CalcNetPay(double gPay, double ss, double med)
 {
  return gPay - (ss + med + (BUSPASS/4));
 }

}

Morning Arrays and loops


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArraysAndLoops2
{
    class Program
    {
        /// 
        /// This program will create an array
        /// populate and array
        /// Display it
        /// sum and average the contents
        /// 
       
        static void Main(string[] args)
        {
            Program p = new Program();
            string choice="y";
            while (choice != "n" && choice != "N")
            {
                p.CreateArray();
                p.ParallelArrays();
                Console.WriteLine("Do you want enter more payments? Y/N");
                choice = Console.ReadLine();
            }
            Console.ReadKey();
        }

        private void CreateArray()
        {
            //double[] payments = new double[5];
            //payments[0] = 234.5;
            //payments[1] = 45.6;
            //payments[2] = 100;
            //payments[3] = 37.98;
            //payments[4] = 223;

            //int[] ray;
            //ray = new int[] { 45, 2, 3, 7, 22 };

            Console.WriteLine("How many payments do you want to enter");
            int number = int.Parse(Console.ReadLine());

            double[] payments = new double[number];

            for (int i = 0; i < number; i++)
            {
                Console.WriteLine(payments[i]);
            }//end for

            FillArray(payments, number);
        }//end create array

        private void FillArray(double[] paymnts, int size)
        {
            for (int i = 0; i < size; i++)
            {
                Console.WriteLine("Enter Payment");
                paymnts[i] = double.Parse(Console.ReadLine());
            }// end for
            DisplayArray(paymnts, size);
        }//end of Fill array

        private void DisplayArray(double[] pmts, int size)
        {
            Console.WriteLine("************************\n");
          
            //Console.Clear();
            for (int i = 0; i < size; i++)
            {
                Console.WriteLine(pmts[i]);
            }//end for
            SumAndAverage(pmts, size);
        }//end Display

        private void SumAndAverage(double[] pay, int size)
        {
            double total = 0;
            for (int i = 0; i < size; i++)
            {
                total += pay[i]; //total=total + pay[i] -= *= %= /=
            }
            Console.WriteLine("The total is {0}", total);
            double average = total / pay.Length;
            Console.WriteLine("the average is {0}", average);
        }//end sum and average

        private void ParallelArrays()
        {
            int[] myArray1 = new int[] { 2, 3, 54, 6, 8 };
            int[] myArray2 = new int[] { 3, 5, 2, 12, 4 };

            for (int i = 0; i < myArray1.Length; i++)
            {
                Console.WriteLine(myArray1[i] * myArray2[i]);
            }
        }

    }//end class
}

Monday, October 17, 2011

Loops and Arrays

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArraysAndLoops
{
    class Program
    {

        /*This program will have three methods
         * one to create an array
         * one to populate it
         * and one to display it
         */
        static void Main(string[] args)
        {
            Program p = new Program();
            string exit = "y";
            while (exit != "n" && exit !="N")
            {
                p.CreateArray();
                Console.WriteLine("Do you want to continue y/n");
                exit = Console.ReadLine();
            }
            p.PauseIt();
        }

        //this method
        //creates an array
        private void CreateArray()
        {

            Console.WriteLine("How many payments do you want to enter?");
            int number = int.Parse(Console.ReadLine());
            double[] payments= new double[number];

            FillArray(payments, number);

            //double[] pmts = new double[] { 12.95, 34, 21.4, 43 };
            //payments[0] = 255;
            //payments[1] = 34.5;
            //payments[2] = 44.5;
            //payments[3] = 34;
            //payments[4] = 34.5;


        }

        private void FillArray(double[] payArray, int size)
        {
            //for loop
            for (int i=0; i < size; i++)
            {
                Console.WriteLine("Enter a payment");

                payArray[i] = double.Parse(Console.ReadLine());
            }//end for
            DisplayArray(payArray, size); //call DisplayArrayMethod
           
        }//end fill array

        private void DisplayArray(double[] pmt, int size)
        {
            Console.WriteLine("***********************");
            int x = 0;
            while (x < size)
            {
                Console.WriteLine(pmt[x]);
                x++;

                /*
                 * +=  (number += 10) same as (number= number + 10);
                -= minus (number -=10) same as (number=number-10)
                -- decrement subtract one each time
                *= (number *=10) same as (number=number*10)
                %=(number %=10) same as (number=number%10)
                /=(number /=10) same as (number=number/10)
                  */
            }//end while
            Sum(pmt, size);
        } //end display

        private void Sum(double[] payment, int size)
        {
            double total = 0;
            for (int i = 0; i < size; i++)
            {
                total += payment[i];
                //weight = grades[i] * credits[i];
            }
            double average = total / size;
            Console.WriteLine("the total is {0}", total);
            Console.WriteLine("the Average is {0}",average);
        }

        private void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }//end PauseIt



    }//end class
}

Arrays

An array says your book, "represents a fixed number of elements of the same type." An array, for instance can be a set of integers or a set of doubles or strings. The set can be accessed under a single variable name.

You use square brackets [] to signify an array. The following declares an array of integers with 5 elements

int[] myArray=new int[5];

Each element in an array has an index number. We can use these indexes to assign or access values in an array. Indexes always begin with 0

myArray[0]=5;
myArray[1]=12;
myArray[2]=7;
myArray[3]=74;
myArray[4]=9;

Console.WriteLine("The fourth element of the array is {0}",myArray[3]);

Here is another way to declare an array. This declaration declares a string array and assigns the values at the moment when the array is created

string[ ] weekdays =new string[ ]
       {"Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

The values are still indexed 0 to 6


Array work naturally with loops. You can easily use a loop to assign values:


for (int i=0; i<size;i++)
{
     Console.WriteLine("Enter an Integer");
     myArray[i]=int.Parse(Console.ReadLine());

}

Arrays can be passed as a parameter to methods and they can be returned by a method.

private void CreateArray()
{
    double[ ] payments = new double[5];
    FillArray(payments, 5);
}

private void FillArray(double[ ] pmts, int size)
{
    int x=0;
   while (x < size)
  {
     Console.WriteLine("Enter Payment Amount");
     pmts[x]=double.Parse(Console.ReadLine());
     x++;
  }
}

Apps

The term "app" is short for application, but it has come to have a special meaning when applied to mobile devices such as phones, mp3 players and tablets. To some extent, these apps, like the term, are abbreviated. They are streamlined to run on the limited resources of a phone or tablet. That isn't to say that some of them aren't quite complex, but no matter how sophisticated, they must run within the constraints of the device they are on.

The question is how important is it for a student to get into the app market, and, if it is important, what skills do they need to get a foot in the door.

Apps have become big business, just as a decade ago every company had to have a web site, now every company has to have an app on your phone. Apps are rapidly becoming the predominate way of accessing the internet.

In September 2010 Chris Anderson wrote an article for Wired called The Web is Dead, Long Live the Internet In it he said:

 Over the past few years, one of the most important shifts in the digital world has been the move from the wide-open Web to semiclosed platforms that use the Internet for transport but not the browser for display. It’s driven primarily by the rise of the iPhone model of mobile computing, and it’s a world Google can’t crawl, one where HTML doesn’t rule. And it’s the world that consumers are increasingly choosing, not because they’re rejecting the idea of the Web but because these dedicated platforms often just work better or fit better into their lives (the screen comes to them, they don’t have to go to the screen). The fact that it’s easier for companies to make money on these platforms only cements the trend. Producers and consumers agree: The Web is not the culmination of the digital revolution.

And the shift is only accelerating. Within five years, Morgan Stanley projects, the number of users accessing the Net from mobile devices will surpass the number who access it from PCs. Because the screens are smaller, such mobile traffic tends to be driven by specialty software, mostly apps, designed for a single purpose. For the sake of the optimized experience on mobile devices, users forgo the general-purpose browser. They use the Net, but not the Web. Fast beats flexible.

http://www.wired.com/magazine/2010/08/ff_webrip/all/1

Sara Perez in Read Write Moblie notes: Native data applications, such as those installed on smartphones like the iPhone and devices running Android, now account for 50% of all mobile data volume according to a new report from Finnish mobile analytics company Zokem. In a global smartphone study released this month, the company found that while the mobile Web browser was still the most popular smartphone "app," the use of native apps outside the browser is growing faster than mobile browsing itself.

Cisco networks notes the following:

Global mobile data traffic grew 2.6-fold in 2010, nearly tripling for the third year in a row. The 2010 mobile data traffic growth rate was higher than anticipated. Last year's forecast projected that the growth rate would be 149 percent. This year's estimate is that global mobile data traffic grew 159 percent in 2010

Last year's mobile data traffic was three times the size of the entire global Internet in 2000. Global mobile data traffic in 2010 (237 petabytes per month) was over three times greater than the total global Internet traffic in 2000 (75 petabytes per month).

Mobile video traffic will exceed 50 percent for the first time in 2011. Mobile video traffic was 49.8 percent of total mobile data traffic at the end of 2010, and will account for 52.8 percent of traffic by the end of 2011.

http://www.cisco.com/en/US/solutions/collateral/ns341/ns525/ns537/ns705/ns827/white_paper_c11-520862.html

Companies are advertising for programmers to create apps. Typically they want people who can program for Apple's IOS and also for Android. Some also want Window's phone developers. Simply Hired had scores of listing for IPhone developer and nearly equal listings for Android developers. There were several listings for Windows phones as well.

The financial model for these apps is still developing. Many are free. They either generate no revenue for the app creator or they generate revenue by incorporating advertisements. Company based apps are usually free, the app itself being a form of advertising. Many other free apps are "lite" versions which encourage you to upgrade to a more feature rich version for a price. Some apps are sold at a 99 cent level. If an app takes off and is downloaded often enough this can add up to significant revenue. Other, usually serious productivity apps, such as Quick Office, charge comparatively large fees for download. But even these fees are miniscule compared to the prices of comparable software for the PC. An expensive app might be priced around 25 dollars, whereas its pc equivalent would be hundreds.

For a student, then there would seem to be two opportunities. One would be to work for a company that wants to build and distribute apps to support its business customers and processes. Another is to build their own apps and try to sell them in the app stores.


Skills Required to Create Apps

First let's consider what apps do:

  • They must use disk and memory resources efficiently since these are limited on mobile devices
  • They must surrender focus gracefully, especially on phones where they must recede to allow the phone call to take precedence.
  • They must thread processes to allow both foreground and background processing
  • They often store data locally for short terms (some for longer)
  • They usually read from and write to cloud data sources
  • They need to refresh on receiving focus
  • They usually keep the location and status of the user
  • Most apps listen for data and can pass alerts to the user
  • They need a simple, clear GUI
  • Many scale to the device with a different look on a phone than a tablet

Let's be clear, to develop apps a programmer still needs all the basic programming skills. He or she must know how to use programming structures such a selection, repetition and arrays. He or she must know how to create appropriate methods, etc. In addition they should have a good understanding of object oriented principles especially inheritance, since much mobile programming involves extending objects that are provided by the development kit.

Additionally, a developer should learn to thread applications, separating foreground and background operations. This is an important skill for surrendering focus to a phone call or another application

The developer should know how to find and access services, both on the phone and the cloud. These include the GPS services and various data services

Basic database skills for storing and retrieving data are also valuable.


Specific Platform requirements

IPhone| IPad| IPod

The tools for IOS development are only available on the MAC. IOS Apps are developed in Object C using XCode. All apps must be processed and approved by Apple and distributed through Apple's AppStore

Here is Apple's">Developer site

Here is an example of Objective C code for a hello world IPhone app

Android

The primary tools for Android are Java and xml through the Android SDK. There are several possible distributors for Android Apps, the largest of which is Google. You can also self distribute if you wish.

Here is the link to the Android Developers guide

Windows Phones

Windows phones use Silverlight with its XAML xml and C# or alternatively XBoxes XNA platform with C#.

Here is Microsoft's phone development site

It is also possible to create phone apps in all these platforms using HTML5. HTML5 apps are run through the phones browser. Microsoft has announced that its next OS, Windows 8 will work across hardware platforms and be based on HTML 5 and JavaScript. I am still unclear as to what that implementation will look like.


This is just a draft of the topic. I will try to expand on it more over time. Please feel free to comment and suggest additions or changes

Tuesday, October 11, 2011

Morning Class Selection statements

Here is the code we did in class with comments


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SelectionExamples
{
    class Program
    {
        /*******************
         * this program has examples of 
         * if statements including an embedded if
         * and an if else statement
         * steve Conger 10/11/2011 
         * ****************************/

        static void Main(string[] args)
        {
            Program prog = new Program();
            //prog.SimpleIf();
            prog.IfElseIfExample();
            prog.PauseIt();

        }

        private void SimpleIf()
        {
            //this is not so simple an if any more
            //declare an integer
            //this is assigned a value by the "out" parameter
            //two lines down
            int number = 0;
            Console.WriteLine("Enter an integer");

            //try parse returns true or false
            //true if the number can be converted to an integer
            //otherwise false. If it is true it passes the 
            //interger value "out" to the number variable
            //declared above
            bool isInteger = int.TryParse(Console.ReadLine(),out number);

            //below is an example of an imbedded if
            //if it is a good number test it 
            if (isInteger == true)
            {
                //never get to this if, if it is not a number
                if (number % 2 == 0)
                {
                    Console.WriteLine("the number is even");
                }
                else
                {
                    Console.WriteLine("the number is odd");
                }
            }
            else
            {
                Console.WriteLine("Not a valid number");
            }
        }

        private void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }//end PauseIt

        private void IfElseIfExample()
        {
            Console.WriteLine("Enter a test score");
            int score = int.Parse(Console.ReadLine());

            string grade=null; //initializes the string though to nothing

            //below is an if, else if statement. It allows you to test 
            // a value against a sequence of ranges
            //it is important that the sequence be correct
            if (score >= 90)
            {
                grade = "A";
            }
            else if (score >= 80)
            {
                grade = "B";
            }
            else if (score >= 70)
            {
                grade = "C";
            }
            else if (score >= 60)
            {
                grade = "D";
            }
            else
            {
                grade = "F";
            }
            Console.WriteLine("your grade is {0}", grade);
        }//end if else if
        
    }//end Program

    
}

Monday, October 10, 2011

If statements

Here is the code from the evening class



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IfExamples
{
    class IfStatements
    {
        static void Main(string[] args)
        {
            IfStatements ifs = new IfStatements();
            //ifs.SimpleIfStatement();
            //ifs.IfElseExample();
            ifs.SwitchExample();
            ifs.PauseIt();
        }//end main

        private void SimpleIfStatement()
        {
            Console.WriteLine("Enter an age");
            int age = int.Parse(Console.ReadLine());
           //equality ==
            //!= not equal

            if (age > 75)
            {
                Console.WriteLine("You are old");
            }
            else
            {
                Console.WriteLine("You are a spring chicken");
            }
        }//end SimpleIf

        private void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();


        }//end PauseIt

        private void IfElseExample()
        {
            bool isInteger;
            int score;
            Console.WriteLine("Enter your test Score");
             isInteger= int.TryParse(Console.ReadLine(), out score);

             if (isInteger == false)
             {
                 Console.WriteLine("Next time enter a number");
                 return;
             }

            int grade = 0;

            if (score >= 90)
            {
                grade = 4;
            }
            else if (score >= 80)
            {
                grade = 3;
            }
            else if (score >= 70)
            {
                grade = 2;
            }
            else if (score >= 60)
            {
                grade = 1;
            }
            else
            {
                grade = 0;
            }

            Console.WriteLine("Your Grade is {0}", grade);
        }//end ifelse

        private void SwitchExample()
        {
            int choice;
            Console.WriteLine("Choose which method to run");
            Console.WriteLine("1: SimpleIfStatement");
            Console.WriteLine("2: IfElseExample");
            Console.WriteLine("3: Exit");

            choice = int.Parse(Console.ReadLine());

            switch (choice)
            {
                case 1:
                    SimpleIfStatement();
                    break;
                case 2:
                    IfElseExample();
                    break;
                case 3:
                    PauseIt();
                    break;
                default:
                    Console.WriteLine("Not a valid choice");
                    break;
            }

        }//end switch

        //if (number > 0 && number < 100) and
        //if (number < 0 || number > 100) or

    }//end class
}

ITC 110 Assignment 2 in Java

Here is the Java equivalent of Assignment 2


package Income;
import java.util.Scanner;

public class NetIncomeCalculator {

 /**
  * This program calculates gross pay
  * and net pay given deductions in 
  * Social Security, medicare and a bus
  * pass. This is the equivalent of
  * Assignment two in C# in ITC 110
  * Steve Conger 10/10/2011
  */
 
 //declaring constants
 final double SOCIALSECURITY = .09;
 final double MEDICARE=.03;
 final int BUSPASS=25;
   
 public static void main(String[] args) {
  //declare and instantiate the class
  //to load it (main being static is
  //already loaded into memory
  NetIncomeCalculator netcalc = new NetIncomeCalculator();
  //call the starting method
  netcalc.Display();
 }
 
 private void Display()
 {
  //get input
  //the scanner is an object to read from the console
  Scanner reader = new Scanner(System.in);
  System.out.println("Enter the number of hours worked");
  double hours = reader.nextDouble();
  System.out.println("Enter your rate per hour");
  double rate=reader.nextDouble();
  
  //call the methods to do the calculations
  double grossPay=CalcIncome(hours, rate);
  double socialSec = CalcSocialSecurity(grossPay);
  double medicare = CalcMedicare(grossPay);
  double netPay=CalcNetPay(grossPay, socialSec, medicare);
  
  //outputs
  System.out.println("Your gross income is " + grossPay);
  System.out.println("Your Social Security deduction is " + socialSec);
  System.out.println("Your Medicare deduction is " + medicare);
  System.out.println("Your Bus pass deduction is " + BUSPASS);
  System.out.println("Your net pay is " + netPay);
 }
 
 private double CalcIncome(double hrs, double rt)
 {
  double gross=0;
  //check to see if the hours are more than forty
  //if they are pay time and a half for overtime
  //if not just pay the rate of pay
  if (hrs > 40)
  {
   gross=rt * (40 + ((hrs-40)*1.5));
  }
  else
  {
   gross = rt * hrs;
  }
  return gross;
 }
 
 private double CalcSocialSecurity(double gPay)
 {
  return gPay * SOCIALSECURITY;
 }
 
 private double CalcMedicare(double gPay)
 {
  return gPay * MEDICARE;
 }
 
 private double CalcNetPay(double gPay, double ss, double med)
 {
  return gPay - (ss + med + BUSPASS);
 }

}

Here is the output from the program


Enter the number of hours worked
45
Enter your rate per hour
25
Your gross income is 1187.5
Your Social Security deduction is 106.875
Your Medicare deduction is 35.625
Your Bus pass deduction is 25
Your net pay is 1020.0

ITC 110 Assignment 1 in Java

This is the Java equivalent of the first ITC 110 assignment. I will do the other assignments in ITC 110 and also post them here


package Mileage;
import java.util.Scanner;
import java.io.*;
public class CalcMileage {

 /**
  * This is a simple program to Calculate
  * miles per gallon
  * it is the equivalent to ITC110
  * assignment 1
  * steve conger 9-26-2011
  */
 public static void main(String[] args) {
  //declare Scanner
  Scanner reader = new Scanner(System.in);
  //declare variables
  double beginMileage;
  double endMileage;
  double gallons;
  double pricePerGallon;
  double milesPerGallon;
  double costPerMile;
  //get input
  System.out.println("Enter the beginning mileage");
  beginMileage=reader.nextDouble();
  System.out.println("Enter the ending mileage");
  endMileage=reader.nextDouble();
  System.out.println("Enter the number of gallons");
  gallons=reader.nextDouble();
  System.out.println("Enter the price per gallon");
  pricePerGallon=reader.nextDouble();
  
  //do processing of input
  milesPerGallon=(endMileage-beginMileage)/gallons;
  costPerMile=pricePerGallon /(endMileage-beginMileage);
  
  //output results
  System.out.print("Your miles per gallon is ");
  System.out.format("%.2f",milesPerGallon);
  System.out.println();
  System.out.print("the cost per mile is ");
  System.out.format("%.2f",costPerMile);
 }

}

Thursday, October 6, 2011

Books and Websites

Here is a list of books and websites you might fine useful to help you with C#

Books

  • Head First C#, O'Reilly, ISBN 978-0596514822
  • Programming C#, Jeff Liberty, O'Relly, ISBM 978-059600699
  • Sam's Teach Yourself, the C# Language in 21 days, Bradley Jones, Sams, ISBN 978-0672325465
  • Murach's C# 2010, Murach and Associates, ISBN 978-1890774592

Web Sites

http://www.msdn.microsoft.com MSDN Microsoft's development Network

http://www.Devx.com DevX development center

Wednesday, October 5, 2011

Start for Assignment 2

Here is the starting code for Assignment 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Assignment2
{
    class Program
    {

        const double SOCSEC = .09;

        static void Main(string[] args)
        {
            Program p = new Program();
            p.Display();
            p.PauseIt();
        }//end main

        private void Display()
        {
            Console.WriteLine("Enter the hours worked this week");
            double hours = double.Parse(Console.ReadLine());
            Console.WriteLine("Enter the rate per hour");
            double rate = double.Parse(Console.ReadLine());

            double weeklyGross = GrossPay(hours, rate);
            Console.WriteLine("Your gross pay is {0:C}", weeklyGross);

            double socialsec = SocialSecurity(weeklyGross);
            Console.WriteLine("Your SS deduction is {0:C}", socialsec);


        }//end Display

        double GrossPay(double weeklyHours, double hourlyRate)
        {
            double gross =0;
            if (weeklyHours > 40)
            {
                gross = hourlyRate * (40 + ((weeklyHours - 40) * 1.5));
            }
            else
            {
                gross = hourlyRate * weeklyHours;
            }
            return gross;
        }//end GrossPay

        private void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }//end PauseIt

        private double SocialSecurity(double grossWeeklyPay)
        {
            return grossWeeklyPay * SOCSEC;
        }
    }//end Program
}//end namespace

Notes for Assignment 2

Remember to break it into methods. Each method should do one thing. For example, one method can calculate the gross pay, another method can deduct social security, etc.

To calculate Overtime we need to us an if statement. We need to do one of two things depending on if the hours are greater than 40 or 40 or less. This can be set up as follows:

if(hours > 40)
{
     pay=rate * (40 + ((hours - 40) * 1.5);
}
else
{
    pay=rate * hours;
}

If the hours are greater than forty, we multiply the rate times forty (because we know we have over forty hours and forty of them are paid at the regular rate) and then add the hours over forty times rate time 1.5 to get time and a half. The parenthesis are necessary to control the order of operations. We want the subtraction to occur first, then the multiplication, then the addition. If, on the other hand, the hours are 40 or less, we just multiply hours times the rate of pay.

For the assignment, you don't have to display the overtime pay separate from the regular pay. You can just display the Gross (total) pay, the deductions and the Net pay (what's left over). Though, if you want to add a challenge you can separate the two in the display.

Tuesday, October 4, 2011

Methods Morning Class

Here is the Morning class's sample code for methods. It is a little different from the evening class. I did not comment it nearly as thoroughly

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Methods
{
    class Program
    {
        static void Main(string[] args)
        {
            Program prog = new Program();
            prog.Display();
            prog.PauseIt();
        }//end of Main

       private void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }//end of PauseIt

       private void Display()
       {
           Console.WriteLine("Enter the beginning mileage");
           double beginningMileage = double.Parse(Console.ReadLine());

           Console.WriteLine("Enter the ending mileage");
           double endingMileage = double.Parse(Console.ReadLine());

           double miles = TotalMiles(beginningMileage, endingMileage);

           Console.WriteLine("\nYour total miles is {0}",miles);

           Console.WriteLine("Enter the number of Gallons");
           double gallons=double.Parse(Console.ReadLine());

           double milesPerGal = MilesPerGallon(miles, gallons);
           Console.WriteLine("Your miles per gallon is {0}", milesPerGal);
           
       }//end Display

       private double TotalMiles(double startMiles, double endMiles )
       {
           return endMiles - startMiles;
       }//Total Miles

       private double MilesPerGallon(double totalMiles, double gals)
       {
           double mpg = totalMiles / gals;
           return mpg;
       }//end MilesPerGallon

    }//end of program class

}//end of namespace

Monday, October 3, 2011

Methods Example

Here is our example from class with extensive comments

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace methodsExample
{
    class Program
    {
        /*********************
         * the point of this excercise is to show
         * how to break a program into methods
         * we have a display method and seperate
         * methods to calcualte the gas mileage
         * and the cost per mile.
         * the point of breaking a program into methods
         * is to divide the work and make it easier
         * to maintain, debug and understand.
         * Ideally each method should do one thing
         * that way it is obvious where to look if
         * something goes wrong
         * Steve Conger 10/4/2011 */

        static void Main(string[] args)
        {
            //a static method is loaded automatically
            //into RAM, but the rest of the class is not
            //so we need to "instantiate" the class
            //to load it into memory where it can be used
            Program p = new Program();
            p.Display(); //call the display method
            p.PauseIt();// call the PauseIT class
            
        }

        //void methods don't return a value
        //they just do their thing
        private void Display()
        {
            //inputs
            //just like what we did in the first assignment
            Console.WriteLine("Enter the Mileage");
             double mileage = double.Parse(Console.ReadLine());
             Console.WriteLine("Enter The Gallons");
             double gals = double.Parse(Console.ReadLine());
             Console.WriteLine("Enter The price per gallon");
             double price = double.Parse(Console.ReadLine());
            //outputs
             Console.WriteLine("Your miles per gallon is {0:F2}", 
                 CalculateGasMileage(mileage, gals));//calls the CalculateGasMileage 
            //as part of the write line. You can only do this if the
            //method returns a value

            //this is another way to do it
            //here we assign the returned result of the method
            //to a new variable
            double mpg=CalculateGasMileage(mileage, gals);

            //we can use that variable in the writeline instead of calling
            //the method again
            Console.WriteLine("Your cost per mile is {0:C}",
                CalculateCostPerMile(mpg,price));

           
        }

        //this method returns a double
        //it takes two parameters that are give values
        //when the method is called in the Display() method above
        private double CalculateGasMileage(double miles, double gallons)
        {
            double milesPerGallon;
            milesPerGallon = miles / gallons; 
            return milesPerGallon;
        }

        private double CalculateCostPerMile(double milesPerGal, double pricePerGallon)
        {
            //double costPerGallon=0;
            //this is a different way to return a value
            //you can return the equation directly
            return pricePerGallon / milesPerGal;
        }

        private void PauseIt()
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
}