Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, November 9, 2011

Java Equivalent of ITC 110 Assignment 6

Here is the code for the BMI Class


public class BMI {

 /**
  * This class calculates Body
  * Mass Index
  */
 //fields
 private int weight;
 private int feet;
 private int inches;
 private int totalHeightInInches;
 
 //constructors
 public BMI(){
  weight=0;
  feet=0;
  inches=0;
  totalHeightInInches=0;
 }
 
 public BMI(int weightInPounds, int heightInFeet, int additionalInches)
 {
  SetWeight(weightInPounds);
  SetHeightInFeet(heightInFeet);
  SetRemainingInches(additionalInches);
  totalHeightInInches=0;
 }
 
 //mutators and accessors
 public void SetWeight(int w)
 {
    weight=w;
 }
 
 public int GetWeight()
 {
  return weight;
 }
 
 public void SetHeightInFeet(int ft)
 {
  feet=ft;
 }
 
 public int GetHeightInFeet()
 {
  return feet;
 }
 
 public void SetRemainingInches(int inch)
 {
  inches=inch;
 }
 
 public int GetRemainingInches()
 {
  return inches;
 }
 
 //methods
 
 private void CalculateTotalHeightInInches()
 {
  totalHeightInInches=(feet*12)+inches;
 }
 
 public double CalculateBMI()
 {
  CalculateTotalHeightInInches();
  return (double)GetWeight() * 703/(double)
    (totalHeightInInches * totalHeightInInches);
 
 }
 
 public String BMIEvaluation(){
  double b = CalculateBMI();
  String eval="";
  if (b > 30)
   eval="Obese";
  else if (b >24.9)
   eval="Overweight";
  else if (b > 18.4)
   eval="Normal";
  else
   eval="Underweight";
  
  return eval;
   
 }
 
 
 
}


Here is the program class with the main. You could make a display class that is called by the main. That would be a better structure, but I did not specify that as a requirement

import java.util.Scanner;
public class Program {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Scanner scan=new Scanner(System.in);
  
  System.out.println("Enter your wieght in pounds");
  int lbs = scan.nextInt();
  
  System.out.println("enter your height in feet");
  int ft = scan.nextInt();
  
  System.out.println("enter any Remaining inches");
  int inch = scan.nextInt();
  
  BMI bmi = new BMI(lbs, ft, inch);
  double b = bmi.CalculateBMI();
  
  System.out.println("Your BM! is " + b);
  String badNews=bmi.BMIEvaluation();
  System.out.println(badNews);

 }

}

Here is the output



Enter your wieght in pounds
180
enter your height in feet
5
enter any Remaining inches
10
Your BM! is 25.824489795918367
Overweight

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 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);
  
 }
 

}

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));
 }

}

Monday, October 10, 2011

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);
 }

}

Saturday, March 12, 2011

Vertical and Horizontal layouts

Here is the Android app again, but now the layout varies with the aspect of the phone.
Mostly this just involved the addition of a new folder layout-land, and an additional main.xml file. Here is a picture of the files in the app:



I did add some slight changes to the original main.xml for formatting:



res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textSize="24.5sp"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/txtprompt"
android:textSize="16.5sp"/>

<EditText
android:id="@+id/field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"/>

<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/tipgroup">

<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ten"
/>

<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fifteen" />
<RadioButton
android:id="@+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/twenty" />

</RadioGroup>


<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/buttonText"
android:id="@+id/calc" />

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/result"
android:textSize="16.5sp"/>


</LinearLayout>

Here is the horizontal layout. (to turn the Emulator horizontal in Windows click ctrl and F11)



res/layout-land/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="15dip"
android:orientation="horizontal">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="20dip"
android:paddingRight="20dip"
>


<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/hello"
android:textSize="24.5sp"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/txtprompt"
android:textSize="16.5sp"/>

<EditText
android:id="@+id/field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"/>



<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/tipgroup">

<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ten"
/>

<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fifteen" />
<RadioButton
android:id="@+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/twenty" />

</RadioGroup>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/buttonText"
android:id="@+id/calc" />

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/result"
android:textSize="16.5sp"/>
</LinearLayout>
</LinearLayout>

Here is the code for CalculateTips.Java


package tips.spconger.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import java.text.NumberFormat;

public class CalculateTips extends Activity implements Button.OnClickListener{
/** Called when the activity is first created. */
private RadioButton rb1;
private RadioButton rb2;
private RadioButton rb3;
private Button b1;
private EditText et;
private TextView t1;
private double tip;
private EditText et2;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.field);
rb1=(RadioButton)findViewById(R.id.radio1);
rb2=(RadioButton)findViewById(R.id.radio2);
rb3=(RadioButton)findViewById(R.id.radio3);
b1=(Button)findViewById(R.id.calc);
b1.setOnClickListener(this);
t1=(TextView)findViewById(R.id.result);

}

@Override
public void onClick(View v) {
double meal=Double.parseDouble(et.getText().toString());

if(v == b1)
{


if(rb1.isChecked() == true){
tip = meal * .1;

}

if(rb2.isChecked() == true){
tip = meal * .15;

}

if(rb3.isChecked() == true){
tip = meal * .2;

}

NumberFormat nf = NumberFormat.getCurrencyInstance();
t1.setText("the tip is " + nf.format(tip));
}
}
}

Saturday, March 5, 2011

First Android App

I have made my first android app. It is a simple program that calculates a tip for a meal at a restaurant. It use a TextView object to display the title, And EditView to allow users to enter an amount, a RadioGroup with three RadioButtons, a Button and another TextView to display the results. Here is a picture of the Android similuator with the program running.



Here is a view of the files. I actually only modified three files: CalculateTips.Java, Main.xml and Strings.xml



Here is the xml in Main.xml that sets up the Android form:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/txtprompt"/>

<EditText
android:id="@+id/field"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"/>

<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content">
android:orientation="vertical"
android:id="@+id/tipgroup"

<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/ten" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/fifteen" />
<RadioButton
android:id="@+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/twenty" />

</RadioGroup>
<Button
android:id="@+id/calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonText"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/result"/>

</LinearLayout>

Here is the code for Strings.xml. This file is used to store string values used by the controls.

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Tip Calculator!</string>
<string name="app_name">Tips</string>
<string name="txtprompt">Enter Meal Amount</string>
<string name="ten">Ten Percent</string>
<string name="fifteen">Fifteen Percent</string>
<string name="twenty">Twenty Percent</string>
<string name="buttonText">Calculate Tip</string>
</resources>

Finally, here is the Java code:

CalculateTips.java

package tips.spconger.com;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class CalculateTips extends Activity implements Button.OnClickListener{
/** Called when the activity is first created. */
private RadioButton rb1;
private RadioButton rb2;
private RadioButton rb3;
private Button b1;
private EditText et;
private TextView t1;
private double tip;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText)findViewById(R.id.field);
rb1=(RadioButton)findViewById(R.id.radio1);
rb2=(RadioButton)findViewById(R.id.radio2);
rb3=(RadioButton)findViewById(R.id.radio3);
b1=(Button)findViewById(R.id.calc);
b1.setOnClickListener(this);
t1=(TextView)findViewById(R.id.result);
}

@Override
public void onClick(View v) {
double meal=Double.parseDouble(et.getText().toString());

if(v == b1)
{
if(rb1.isChecked() == true){
tip = meal * .1;

}

if(rb2.isChecked() == true){
tip = meal * .15;

}

if(rb3.isChecked() == true){
tip = meal * .2;

}
t1.setText("the tip is " + tip);
}
}
}


The Java code declare an instance of each of the objects and then uses R.Id to associate it with the control in the Main.xml. R is an xml file that is automatically generated by the Android sdk. The button is given the OnClickListener method which is executed whenever the button is clicked.

Monday, February 28, 2011

Classes and arrays

Program.java

import java.util.*;
public class Program {

/**
* @param args
*/
public static void main(String[] args) {

TestScores ts = new TestScores(5);
Scanner scan=new Scanner(System.in);
int score=0;
for(int i=0; i<5; i++)
{

System.out.println("Enter a score");
score=scan.nextInt();

ts.Addscore(i, score);
}

int[] scores2=ts.GetScores();

for (int i=0;i<5;i++)
{
System.out.println(scores2[i]);
}

}

}

TestScores.Java

public class TestScores {

private int number;
private int[] scores;

public TestScores(int numberOfScores)
{
number=numberOfScores;
scores=new int[number];
}

public void Addscore(int i, int score)
{
scores[i]=score;
}

public int[] GetScores()
{
return scores;
}

}

Sunday, February 27, 2011

Java classes

Here is the code for the java classes that I have been working on. These classes show how to implement an interface called IActivity. The classes are meant to represent a very simple bank account application.

Here is a picture from Eclipse of the files involved:



Here is the UML for the class diagrams that I did before writing the program There have been some modifications to the classes in the process of writing the code that are not reflected in the diagram. Specifically I modified the interface and changed the transactions method into GetDebitTransactions and GetCreditTransactions. Also there were some modifications of the Display class.



Finally, before I give the code for the actual classes. Here is the console transcript that shows how the program looks when running:



Choose an account:
1. Checking
2. Savings
3. HomeEquity/n0 to quit

1
Enter the beginning balance

1000
Enter Your choice, 0 to exit
********************************
*1. Credit *
*2. Debit *
*3. Balance *
*4. Get Transactions *
*5. Get Interest *
********************************
1
Enter the credit amount
250
Enter Your choice, 0 to exit
********************************
*1. Credit *
*2. Debit *
*3. Balance *
*4. Get Transactions *
*5. Get Interest *
********************************
1
Enter the credit amount
1200
Enter Your choice, 0 to exit
********************************
*1. Credit *
*2. Debit *
*3. Balance *
*4. Get Transactions *
*5. Get Interest *
********************************
2
Enter the debit amount
35.96
Enter Your choice, 0 to exit
********************************
*1. Credit *
*2. Debit *
*3. Balance *
*4. Get Transactions *
*5. Get Interest *
********************************
2
Enter the debit amount
813.77
Enter Your choice, 0 to exit
********************************
*1. Credit *
*2. Debit *
*3. Balance *
*4. Get Transactions *
*5. Get Interest *
********************************
2
Enter the debit amount
99.50
Enter Your choice, 0 to exit
********************************
*1. Credit *
*2. Debit *
*3. Balance *
*4. Get Transactions *
*5. Get Interest *
********************************
4
Credits
250.0
1200.0
Debits
35.96
813.77
99.5
Balance
1500.77
Enter Your choice, 0 to exit
********************************
*1. Credit *
*2. Debit *
*3. Balance *
*4. Get Transactions *
*5. Get Interest *
********************************
0


So here are the classes:
IActivity

import java.util.*;
/*******************************************
* this is an interface that contains
* five method definitions one for credits
* one for debits one for getting the balance
* one for getting all debits in a list
* and one for getting all the credits in a list
* An interface forces any class that
* implements it to implement all its methods
* @author Steve
*
********************************************/
public interface IActivity {

public void Credit(double amt);
public void Debit (double amt);
public double GetBalance();
public ArrayList GetDebits();
public ArrayList GetCredits();
}

Program.Java

public class Program {

/**
* This is the starting point of the program
* It contains the main method.
* The only thing the main method will do
* is call the display class.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Display dsplay=new Display();
}

}

Display.Java
import java.util.*;
/***********************************
* The purpose of the display class is
* to gather the input needed and
* to display the output. This display
* class is console, but it could be replaced
* by a form or web page without any changes
* being reguired in the other classes.
* @author Steve
*
*/

public class Display {

//we are declaring the interface as a class
//level variable. At runtime we can assign
//one of the classes that implements this
//interface to the variable.
//this is a core principle of Object oriented
//design and actually one of the elements
//of polymorphism: a child can always be substituted
//for the parent
IActivity actv;
int bal=0;
Scanner scan = new Scanner(System.in);

public Display()
{
Menu();
}

public void Menu()
{
int choice=1;

System.out.println("Choose an account:\n1. Checking\n2. Savings\n3. HomeEquity/n0 to quit");
choice = scan.nextInt();
if (choice==1)
{
SetBalance();
actv = new Checking(bal);
}
else if(choice==2)
{
SetBalance();
actv = new Savings(bal);
}
else if(choice==3)
{
//not defined at this time
return;
}
else if(choice==0)
{
return;
}
else
{
System.out.println("not a valid choice");
Menu();
}

while(choice != 0)
{
System.out.println("Enter Your choice, 0 to exit");


System.out.println("********************************");
System.out.println("*1. Credit *");
System.out.println("*2. Debit *");
System.out.println("*3. Balance *");
System.out.println("*4. Get Transactions *");
System.out.println("*5. Get Interest *");
System.out.println("********************************");

choice = scan.nextInt();

//at this point only the checking options are
//implemented
switch (choice)
{
case 0:
break;
case 1:
AddCredit();
break;
case 2:
AddDebit();
break;
case 3:
GetBalance();
break;
case 4:
GetTransactions();
break;
case 5:
GetInterest();
break;
default:
System.out.println("Not a valid choice");
return;


}


}
}



private void SetBalance()
{
System.out.println("Enter the beginning balance");
bal=scan.nextInt();
}

private void AddCredit(){

System.out.println("Enter the credit amount");
double cr = scan.nextDouble();
actv.Credit(cr);
}

private void AddDebit(){

System.out.println("Enter the debit amount");
double db = scan.nextDouble();
actv.Debit(db);
}

private void GetBalance() {
double balance = actv.GetBalance();
System.out.println("the balance is " + balance);
}

private void GetTransactions(){
ArrayList creditList =actv.GetCredits();
ArrayList debitList=actv.GetDebits();

System.out.println("Credits");
for (int i=0;i<creditList.size();i++)
{
System.out.println(creditList.get(i));
}

System.out.println("Debits");
for (int i=0;i<debitList.size();i++)
{
System.out.println(debitList.get(i));
}
System.out.println("Balance");
System.out.println(actv.GetBalance());

}

private void GetInterest()
{
//not defined
}

}

Checking.Java
import java.util.List;
/***************************************
* this class handles checking deposits
* and withdrawels. It implements the interface
* IActivity and so much implement each or
* its methods
*/

import java.util.*;
public class Checking implements IActivity {

double balance;
//the arraylists below are to keep track
//of the activitires
ArrayList Debits = new ArrayList();
ArrayList Credits= new ArrayList();

//a constructor that takes in the beginning
//balance
public Checking(double balance)
{
//the this keyword differentiates
//the balance that belongs to this class
//from the one that comes through
//the contructors arguments
this.balance=balance;
}

@Override
public void Credit(double amt) {
//add the amount to the balance
//and add it to the list of credit
//transactions
balance += amt;
Credits.add(amt);
}

@Override
public void Debit(double amt) {
//Make sure the result won't
//be negative and then subtract
//the amount from the balance
//and add it to the debit list
if(balance >= (balance-amt))
{
balance -= amt;
Debits.add(amt);
}
}

@Override
public double GetBalance() {

return balance;
}

@Override
public ArrayList GetDebits() {
//we are just returning the list
//the display can figure out what to
//do with it
return Debits;
}

@Override
public ArrayList GetCredits() {
// TODO Auto-generated method stub
return Credits;
}



}

Savings.Java

import java.util.*;

/***************************************
* this class handles savings accounts. It is really
* a mirror of the checking, but adds an interest
* calculation. One could argue that there should
* be another level of abstraction, because there
* is so much that is similar between this and checking.
* Either this class should inherit from checking or
* both should inherit from an abstract class called
* Account
* @author Steve
*
*/
public class Savings implements IActivity {

double balance;
ArrayList credits = new ArrayList();
ArrayList debits=new ArrayList();
final double INTERESTRATE=.04;

public Savings(double balance)
{
this.balance=balance;

}


@Override
public void Credit(double amt) {
balance += amt;
credits.add(amt);
}

@Override
public void Debit(double amt) {
balance -= amt;
debits.add(amt);

}

@Override
public double GetBalance() {
// TODO Auto-generated method stub
return balance;
}

@Override
public ArrayList GetDebits() {
// TODO Auto-generated method stub
return debits;
}

@Override
public ArrayList GetCredits() {
// TODO Auto-generated method stub
return credits;
}

public double CalculateInterest()
{
return 0;
}

}

HomeEquity.Java (not implemented yet)

//public class HomeEquity extends Savings{

//public HomeEquity(){}

/********************************
* this class is not implemented at this time.
* It would inherit from savings and add
* only an extra field that accounts for
* the total equity avaialable
*/
//}

Wednesday, February 9, 2011

Another Java Class with Inheritance

This uses the boat and motorboat classes from the last post. What I have added is a sailboat class that also inherits from boat and added some code to the Program.java file where the main function resides. I am only going to post the changed code here:

SailBoat.java

public class Sailboat extends Boat {
private double mastHeight;
private int numberOfSails;

public void SetMastHeight(double height)
{
mastHeight=height;
}

public double GetMastHeight()
{
return mastHeight;
}

public void SetNumberOfSales(int sails)
{
numberOfSails=sails;
}

public int GetNumberOfSails()
{
return numberOfSails;
}
}

Program.Java

public class Program {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

MotorBoat myBoat=new MotorBoat();
myBoat.setBoatSize(30);
myBoat.setCost(25000);
myBoat.SetHorsePower(20);
double cpf=myBoat.CostPerFoot();


System.out.println("the boat is " + myBoat.getBoatSize()+ " feet long");
System.out.println("the boat costs " + myBoat.getCost() + " dollars");
System.out.println("the horse power is " + myBoat.horsepower );
System.out.println("the cost per foot is " + cpf);

Sailboat myBoat2 = new Sailboat();
myBoat2.setBoatSize(25);
myBoat2.setCost(45000);
myBoat2.SetMastHeight(30);
myBoat2.SetNumberOfSales(2);

System.out.println("*********************************************");
System.out.println("the boat is " + myBoat2.getBoatSize()+ " feet long");
System.out.println("the boat costs " + myBoat2.getCost() + " dollars");
System.out.println("the mast height is " + myBoat2.GetMastHeight() );
System.out.println("the boat has " + myBoat2.GetNumberOfSails() + " sails");
System.out.println("the cost per foot is " + myBoat2.CostPerFoot());

}

}

Here is the output:

the boat is 30 feet long
the boat costs 25000.0 dollars
the horse power is 20.0
the cost per foot is 833.3333333333334
*********************************************
the boat is 25 feet long
the boat costs 45000.0 dollars
the mast height is 30.0
the boat has 2 sails
the cost per foot is 1800.0

Wednesday, February 2, 2011

java classes and Inheritance

Here is a simple case of making a class and extending it (inheriting from it.) First We create a simple boat class.

Boat.java

public class Boat {

//private class fields
private int boatSize;
private double cost;

//public gets and sets (accessors and mutators)
//for the fields
public int getBoatSize()
{
return boatSize;
}
public void setBoatSize(int size)
{
boatSize=size;
}

public double getCost()
{
return cost;

}
public void setCost(double price)
{
cost=price;
}

//a simple public method
public double CostPerFoot()
{
return cost/boatSize;
}
}

Here is the class the extends, inherits from Boat. It gets
all the public methods of the parent

MotorBoat.java

public class MotorBoat extends Boat
{
double horsepower;

public double GetHorsePower()
{
return horsepower;
}
public void SetHorsePower(double hp)
{
horsepower=hp;
}
}

Here is the program class that has the main method
and which uses the motorboat class

Program.java

public class Program {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

MotorBoat myBoat=new MotorBoat();
myBoat.setBoatSize(30);
myBoat.setCost(25000);
myBoat.SetHorsePower(20);
double cpf=myBoat.CostPerFoot();

System.out.println("the boat is " + myBoat.getBoatSize()+ " feet long");
System.out.println("the boat costs " + myBoat.getCost() + " dollars");
System.out.println("the horse power is " + myBoat.horsepower );
System.out.println("the cost per foot is" + cpf);

}

}

Here is the output from the program:

the boat is 30 feet long
the boat costs 25000.0 dollars
the horse power is 20.0
the cost per foot is 833.3333333333334

These classes are still very simple. They don't have constructors
or overridable methods. I will do that next.