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