Triangle Perimeters. Go With The Flow.

| Posted in , , | Posted on 10:14 PM


This is another example of flow control. This is not at all an elegant program. It almost hurts me to post it. Hopefully as I become more comfortable with the language the flow will be nicer on the eyes. This program is a first for me because it tests the input and then asks the user if he/she would like to try again if the input is invalid. I used a while loop for test.



/*
 * This program takes the 3 lengths of a triangle's
 * sides, determines if these are valid lengths,
 * and then computes the perimeter.
 */

package perimeterofatriangle;
import javax.swing.JOptionPane;

/**
 * @author Neil master coder
 */

public class Main {


    public static void main(String[] args) {
       
        //initialize var for triangle sides
        int side1=0, side2=0, side3=0;
       
        //initialize var for continue question
        int question=0;

       
        while (question==0) {

            String stringSide1 = JOptionPane.showInputDialog(null,
                    "Enter the first side " +
                    "of the triangle.");
            String stringSide2 = JOptionPane.showInputDialog(null,
                    "Enter the second side " +
                    "of the triangle.");
            String stringSide3 = JOptionPane.showInputDialog(null,
                    "Enter the third side " +
                    "of the triangle.");

            side1=Integer.parseInt(stringSide1);
            side2=Integer.parseInt(stringSide2);
            side3=Integer.parseInt(stringSide3);

            if ((side1+side2
                (side2+side3
                (side3+side1

                String stringQuestion = JOptionPane.showInputDialog(null,
                        "The triangle you entered is invalid." +
                        " Do you want to try again? " +
                        "Enter 0 (zero) to continue or " +
                        "any other number to quit.");
                question=Integer.parseInt(stringQuestion);
                }
            else{
            if (question==0){
                JOptionPane.showMessageDialog(null, "The perimeter " +
                        "of a triangle having sides " +
                        side1 + " , " +
                        side2 + " and " +
                        side3 + " " +
                        "is " + (side1+side2+side3) +".");
                question++;
            }

        }


    }
    }
}

Sorting Three Integers

| Posted in , , , | Posted on 12:24 PM


For, while, do while, if, if-then... These are all control statements. I'm at the part in my practice where loops come into play as well as controlling when instructions are executed.

The first exercise is a program which will sort three integers from largest to smallest. To do this I used a couple if and else-if statements.






/*
 * This program is meant to prompt the user for
 * three integers, sort those integers from
 * smallest to greatest and then display
 * those integers. It is also an example
 * of if/else control statements.
 */

package sortingthreeintegers;
import javax.swing.JOptionPane;

/**
 * @author Neil master coder
 */
public class Main {

    /**
     * @param args the command line arguments
     */


    public static void main(String[] args) {

        int num1=0, num2=0, num3=0;
        int smallest=0, middle=0, largest=0;

        for (int i=1; i<4; i++) {
        String stringNum = JOptionPane.showInputDialog(null,
                "Enter integer number " + i + " to be"
                + " evaluated." );

        if (i==1)
            num1=Integer.parseInt(stringNum);
            else if(i == 2)
            num2=Integer.parseInt(stringNum);
            else if(i == 3)
            num3=Integer.parseInt(stringNum);

        }

        if ((num1<=num2) && (num1<=num3)){
            smallest = num1;
            if (num2<=num3){
                middle=num2;
                largest=num3;}
            else {
                largest=num2;
                middle=num3;}
        }

        else if((num2 <= num1) && (num2 <= num3)){
            smallest=num2;
            if (num1
                middle=num1;
                largest=num3;}
        }

        else if((num3 <= num1) && (num3 <= num2)){
            smallest=num3;
            if (num2
                middle=num2;
                largest=num1;}
        }

        JOptionPane.showMessageDialog(null, "The numbers arranged "
        + "from smallest to largest are: "
        + smallest + " " + middle + " " +
        largest + ".");

   }


}

Find that Cylinder's Volume! (part II)

| Posted in , , | Posted on 11:41 PM


Computers may be incredibly efficient but they are also equally dumb.

  1. Ask user for radius.
  2. Ask user for cylinder length.
  3. Tell user cylinder volume.
Sounds simple enough... until the program breaks down because the the user gives the computer a bunk number for either the length or radius. Plug in a negative radius and the program will compute a negative volume. Last I checked negative volumes aren't possible, but I could be wrong. Next time I check in with Steven Hawking I'll ask him about negative volumes.

Assuming we want positive volumes then we'd also want positive lengths and radii. Here's a modified version of "Find that Cylinder's Volume" that uses if/else to test the input. If it finds a negative value it prints the error and exits.


/*
 * This is a basic application meant to calculate
 * the area of a circle. It's an improvement on past
 * program because it verifies input as a positive number.
 */

package calculateareaofcircle2;
import javax.swing.JOptionPane;

/**
 * @author Neil
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

    // Prompt user for radius of cylinder and store it as variable
    String stringRadius = JOptionPane.showInputDialog(null, "Enter the"
           + " radius of the cylinder.", "Find that Volume!",
           JOptionPane.QUESTION_MESSAGE);
    // Convert string value to a double variable
    double radius = Double.parseDouble(stringRadius);

if (radius >= 0) {

    // Prompt user for the length of the cylinder and
    // store it as a variable
    String stringLength = JOptionPane.showInputDialog(null, "Enter the"
            + " length of the cylinder.", "Find that Volume!",
            JOptionPane.QUESTION_MESSAGE);
    // Convert string value to a double variable
    double length = Double.parseDouble(stringLength);

    if (length >=0) {

    /*
     * Calculate the volume of the cylinder by first finding the area
     * of the  base and then multiplying it by the length.
     */

    // Declare area, calculate it, and  then store it
    double area = (radius * radius) * 3.141593;

    // Declare volume, calculate it, and then store it
    double volume = area * length;

    // Display result of calculation
    JOptionPane.showMessageDialog(null, "A cylinder that is " + length +
    " long and " + radius + " in radius has a volume of " + volume,
    "Find that Volume!", JOptionPane.QUESTION_MESSAGE);
        }
else {
    JOptionPane.showMessageDialog(null, "The cylinder length must be "
    + "a positive number.");
 }
        }
else {
    JOptionPane.showMessageDialog(null, "The radius must be a positive "
                + "number.");
        }
    }
}

Metric Makes the World Go Round

| Posted in , , | Posted on 5:56 PM

I'm always a fan of European things. Most often this means cars & food. The metric system though... is something I could take or leave. Like most Americans I don't have a natural sense of how far a kilometer is or how heavy a kilogram weighs. Either of these has to be converted into something in the Standard measurement before anything meaningful can be understood. Thank god for Java.

This is a program which will convert a length in feet into a length in meters.


/*
 * This is a simple program to convert feet into meters. Feet are entered
 * as a double value, converted into meters as a double value, and then output.
 * In/out dialogs are generated using the swing JOptionPane class.
 */

package feet2meters;

import javax.swing.JOptionPane;

/**
 * @author Neil
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        //prompt the user to enter the number of feet to be converted
        //and store as a string value
        String stringFeet = JOptionPane.showInputDialog (null,
                "Enter the number of feet to be converted to meters",
                "Feet2Meters!", JOptionPane.QUESTION_MESSAGE);

        //convert feet string value into a double variable
        double feet = Double.parseDouble(stringFeet);

        //initialize meters as double variable and calculate value
        double meters = feet * 0.305;

        //display number of meters calculated from feet given
        JOptionPane.showMessageDialog(null, feet + " feet is equal to " +
                meters + " meters.", "Feet2Meters!",
                JOptionPane.QUESTION_MESSAGE);

    }

}

Area of a Circle

| Posted in , | Posted on 5:50 PM


PI is best served with ice cream, or a cold glass of milk. Sometimes though it goes just fine with some fresh Java. This program takes a given radius (unprompted) and calculates the area of the circle that radius would create.



/* This is a simple program to calculate
 * the area of a circle. To begin, the
 * radius will be a fixed variable.
 */

package calculateareaofcircle;

/**
 *
 * @author Neil
 */
public class Main {

    public static void main(String[] args) {

        double area;
        double radius;

        radius=20;
        area=3.14*radius*radius;

        System.out.println("The area of the circle with a radius of " +
                radius + " is " + area);
    }

}

Coding and Gambling

| Posted in | Posted on 4:41 PM

Wife & laptop in hand we hit the casino the other day. She was excited to catch a concert with some friends and I was excited to play some games and get some practice coding done. Given the environment the programs were nothing challenging. We had a good time though. She loved the concert, I came out even on the tables, and two programs compiled error free.

Find that Cylinder's Volume!

| Posted in , , | Posted on 12:41 AM

Easy.... as.... pi!

/*
* This is a basic application meant to calculate the volume
* of a cylinder given its radius and length
*/

package cylinder_volume;
import javax.swing.JOptionPane;

/*
* @author Neil
*/
public class Main {


public static void main(String[] args) {

// Prompt user for radius of cylinder and store it as variable
String stringRadius = JOptionPane.showInputDialog(null, "Enter the"
+ " radius of the cylinder.", "Find that Volume!",
JOptionPane.QUESTION_MESSAGE);
// Convert string value to a double variable
double radius = Double.parseDouble(stringRadius);

// Prompt user for the length of the cylinder and store it as a variable
String stringLength = JOptionPane.showInputDialog(null, "Enter the"
+ " length of the cylinder.", "Find that Volume!",
JOptionPane.QUESTION_MESSAGE);
// Convert string value to a double variable
double length = Double.parseDouble(stringLength);

/*
* Calculate the volume of the cylinder by first finding the area
* of the base and then multiplying it by the length.
*/

// Declare area, calculate it, and then store it
double area = (radius * radius) * 3.141593;

// Declare volume, calculate it, and then store it
double volume = area * length;

// Display result of calculation
JOptionPane.showMessageDialog(null, "A cylinder that is " + length +
" long and " + radius + " in radius has a volume of " + volume,
"Find that Volume!", JOptionPane.QUESTION_MESSAGE);
}

}

Fahrenheit 2 Celsius

| Posted in , | Posted on 11:53 PM

This is considerably simpler than my banking interest calculation but then again it's late, a weekend, and I just wanted to get some practice code in even if it's nothing spectacular. It's clean and I'm happy with that.

It's a small, short, and sweet program that takes a temperature (Fahrenheit) and converts it to Celsius.


/*
* This is a simple program meant to convert a fahrenheit
* temperature to celsius. It's drawn from Chap 2, Ex 1
*/

package fahrenheit_2_celcius;

// pull in a javax class for gui message boxes
import javax.swing.JOptionPane;

/**
* @author Neil
*/
public class Main {

public static void main(String[] args) {

// prompt user for a fahrenheit temperature and store it in variable
String stringFahrenheit = JOptionPane.showInputDialog (null,
"Enter your temperature" + " in fahrenheit", "Fahrenheit 2 "
+ "Celsius Calculator", JOptionPane.QUESTION_MESSAGE);

// convert stringFahrenheit into double variable
double fahrenheit = Double.parseDouble(stringFahrenheit);

// convert fahrenheit into celcius and store it in variable
double celsius = (5.0/9.0)*(fahrenheit-32.0);

// display converted temperature

JOptionPane.showMessageDialog(null, fahrenheit + " degrees fahrenheit"
+ " is equal to " + celsius + " degrees celsius.", "Fahrenheit 2 "
+ "Celsius Calculator", JOptionPane.QUESTION_MESSAGE);

}

}

Banking & Java

| Posted in , | Posted on 10:55 PM

As a banker of course I gravitated toward a banking related example. This problem asks that given a loan term, apr, and principal what the monthly payment would be. I was more interested in the construction of the code than the underlying math so I lifted the equation from the book.

((loanamount x monthlyinterestrate) / 1 )
/ (1-(1/(1+monthlyinterestrate)^(number of years x 12)))


Yeah...

It's really exciting to have a gui based prompt and not be confined to a terminal. I'm still not really familiar with the JOptionPane. There was another surprise. I thought that having an exponent could be expressed with a carrot aka "^" character. Such is not the case. After a quick Google search I found that you have to use the method Math.pow(number, exponent). Easy enough but it was still a surprise.

package interestcalculation;

/**
* @author Neil
*/

//Pull in Javax class
import javax.swing.JOptionPane;

public class Main {



public static void main(String[] args) {

//Prompt user for annual interest rate
String rateString = JOptionPane.showInputDialog(null, "Enter the Annual" + " Percentage Rate", "Interest Calculator", JOptionPane.QUESTION_MESSAGE);

//Convert rateString into a double variable
double rate = Double.parseDouble(rateString);
double monthlyrate = rate / 1200;

//Prompt user for term of loan in years
String termString = JOptionPane.showInputDialog(null, "Enter the term of" + " the loan in years", "Interest Calculator",
JOptionPane.QUESTION_MESSAGE);

//Convert termString into an double variable;
double term = Double.parseDouble(termString);

//Prompt user for loan amount
String amountString = JOptionPane.showInputDialog(null,
"Enter the full" + " loan amount.", "Interest Calculator",
JOptionPane.QUESTION_MESSAGE);

//Convert amountString into a double variable;
double amount = Double.parseDouble(amountString);

//Calculate Payment
double payment = amount * monthlyrate / (1-1 / Math.pow(1 + monthlyrate, term *12));

//Display Payment

JOptionPane.showMessageDialog(null, "The monthly payment is $"
+ payment);

}

}

Variable Types

| Posted in , | Posted on 10:50 PM

A variable is a data container that well, varies. You have to define it and then indicate what type of data it will contain. int, double, and char are the first examples in the book.

int x; //declare integer variable
/* Occupies 32 bits or 4 bytes, which is: -231 to 231-1 or -2,147,483,648 to 2,147,483,647. */

double x; //declare double variable
/* Occupies 64 bits or 8 bytes, with 14 or 15 significant digits. */

char a; //character variable
/* Occupies 16 bits or 2 bytes, stores a - z, A - Z, 0 - 9, as well as +, - , etc. */

Several variables can be declared in a single statement.

int var1, var2, var3; // three variables are declared in one statement

Variables can also be given a value as they are declared.

int var1=3; //variable declared and given value of 3
int var2=var1+3; //variable declared and given value of an expression

Division of two integers yields an integer. The book gives the example of 5/9. The integer value of this would be 0. 5.0/9 forces a float, double, or something a little bit more accurate.

It's 11:11 pm. Goodnight for now!

Hello World Pt2

| Posted in , , , | Posted on 7:28 PM

After one or two compilation errors I eventually got a clean build. I love the way /* comments look as opposed to //. It's an aesthetic, but you have to enjoy the simple things.


/*

* This is a simple demo displaying "Hello World".
*/

package helloworld;

/**
* @author Neil
*/

public class Main {

public static void main(String[] args) {
System.out.println("Hello World");

}

}

The author suggested pulling in an additional class that enables dialog boxes. This was done by "importing" it. I don't know how people remember these long class names. Maybe it comes with time. Sometimes the IDE will pop up suggestions. It suggested System.out.println but didn't do anything with JOptionPane.showMessageDialog.

/*
* This is a simple demo displaying "Hello World".
*/

package helloworld;

/*Pull in a class that enables a pop up msg box.*/
import javax.swing.JOptionPane;

/**
* @author Neil
*/
public class Main {

public static void main(String[] args) {
/*Output window.*/
JOptionPane.showMessageDialog(null, "Hello World!");

}

}

Yep. The dialog box popped up just like it should have. Huzzah!

Hello World

| Posted in , | Posted on 11:09 AM

And so it begins.

Nearly every programmer begins with the simple task of creating and executing a program to output a single line of text. "Hello World" has often been that line. It's been a long while since I've cracked open a text editor and even longer since firing up a compiler. The basics have escaped me and I've really forgotten how to craft something even so basic as a "Hello World". It's sad; I'm sad!

Tonight I'll be opening the book, launching my favorite IDE, and churning out some code.

Until then... Auf Wiedersehen.

Blog Kickoff

| Posted in , | Posted on 12:03 AM

Benvenuto. Willkommen. Aloha.

Welcome to the kickoff of a brand spanking new blog. It feels like a toast in order, drinks should be shared, and a party to celebrate its launch. So here's a virtual toast. A toast to the success of this blog and its usefulness in my education. Cheers!