Browsing Tag

java

Computer Programming I, Java, Programming Languages

The Rainfall Problem in Java

March 28, 2014

It has been quite a while since I have posted any code in Java. As I was going through some Java questioners, I came across the Rainfall problem. The rainfall problem in java is quite simple, the user is going to enter data, the average participation per day r something, and the output is some statistical information. To keep things interesting, no arrays can be used, so everything needs to be computed on the fly. For our purpose, the user will enter the last 12 months data, an he output will be the minimum, maximum and average participation. This is fairly simple and a great exam or interview question.

Note that the code will check that enteries are non negative numbers.

Here is how this is going to look in Java:

import java.util.Scanner;

public class Rainfall {

 public static void main(String[] args) {

  //variable setup
  Scanner input = new Scanner(System.in);
  String userInput = "";
  double sum = 0.0;
  final int COUNT = 12;
  boolean valid = true;

  //initiazlize variables min and max to something out of range
  double min = 999999999999.9;
  double max = -0.1;
  int min_month = 0;
  int max_month = 0;

  //temp variable
  double curr = 0.0;

  for (int i=0; i < COUNT; i++){

    //user input validation
    do{

		//get user input
        System.out.print("enter the rainfall for month number " + (i+1) +": ");
        userInput=input.nextLine();

		try{

			//convert input to double
			curr = Double.parseDouble(userInput);
			valid = true;

			//throw error if input is less than 0
			if(curr < 0) throw new Exception();

		} catch (Exception e) {

			System.err.println("\nThat was not a valid entry! \nPlease try again.\n");
			valid = false;
									}
   } while (!valid);

   //keep a running total
   sum+= curr;

   //find min
   if(curr < min){
     min = curr;
     min_month = i+1;
   }

   //find max
   if(curr > max){
     max = curr;
     max_month = i+1;
   }

  } //end for loop

  //compute the average
  double avg = sum/COUNT;

  //report the result
  System.out.println("\nThe avg rainfall is " + String.format("%.2f", avg) +
    "\n" + "The min rainfall is " + min + " for month number " + min_month +
    "\n" + "The max rainfall is " + max + " for month number " + max_month );
 }
}

Here is how the output should look like:

wpid-rainfall_output-2014-03-24-03-24.png

Problems, Programming Languages

The Basics Of Classes in Java

October 17, 2013

It has been a little while since I had a chance to write an article, so I figured I am way past due for one. Let us get started.

What are Classes? Classes are essentially blueprints. Much like a blue print for a coffee mug, house or a car. Classes contain a framework on which we can build an Object. Classes are the technical generic framework of an Object. So what are Objects? Well, the text book definition I tend to like is that Objects are instantiation of Classes. They are the “bringing to life” (if I may) of a Class. Let me try to put this into an example. A table in the most generic form would be a flat service supported by legs. This will be the Class. An Object of the table might be a kitchen table of hight h, width w, length l and has 4 rounded edges with round legs. The particulars of the Object are called attributes. We will get back to that in a little bit.

So what can Objects do for us? Well, the must be somehow useful, after all Java is an Object Oriented Programming Language and is by far the most in demand. Objects are useful because we can interact with them. We can use what we call behaviors, to make use of them. Going back to our example, what can we do with a table? We can put something on it and remove something form it. Maybe we can change it’s height by putting it on 4 bricks? I will admit when you think about it a table is a pretty simple Object, but when we see more examples we will see many more attributes and behaviors.

wpid-java-logo-2013-10-18-00-49.jpg

Before we get in to gory detail let us see more ways objects are useful. This following paragraph is mostly to convince you that Objects are indeed useful in any language. First, Objects allow us to create a hierarchy of an Objects that inherit information from their parents. What does that mean? It means that if for example we create a parent Object, call it Shape, we can create a child Object named Rectangle. The Object Shape might only have 1 attribute Name, but the Object Rectangle will have it’s parents attribute Name, and maybe some more information such as it’s sides lengths. Second, Objects allow us to encapsulate data. This means we can keep the internal of the Object hidden and keep the implementation as well as attributes hidden from another user. So in a nut shell I can write a program that uses an Object that I have no direct way to interact with it, aside from public methods. Third, because of encapsulation I can ensure the integrity of the attributes of an Object. For example, I can prevent anyone from leaving the Name of Shape empty. I know this is a little out there for someone that is just starting off, but like I said it is something you are going to have to learn and we will have to visit that later.

All this theory makes me want to code something up. How about that Rectangle class? Here is a problem formal definition:

Create a class Rectangle. The class has attributes length and width, each of which defaults to 1.0. It has methods that calculate the perimeter and the area of the rectangle. It has set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers larger than 1.0 and less than 10.0. Write a program to test class Rectangle.

This is a classic beginner problem and a good review/quiz problem. It shouldn’t take you longer than 10-15 min to figure something like this out. Lets try to work this out together. Like every other Computer Science problem, start by reading the problem at least twice and then start to figure out what is requested from you. Here is my list of requirements:

  1. Create a Rectangle class
  2. Rectangle has 2 attributes (or variables) length and width that are floating point numbers
  3. The attributes of Rectangle are initially set to 1.0.
  4. We need a getter and setter for each attribute
  5. The setter must validate that the number assigned to length or width is no less than 1.0 and no more than 10.0.
  6. Rectangle has to have a method to calculate perimeter and area.
  7. Write a main method that utilize Rectangle class and tests it’s functions.

Great. Now let us start with Java.

Number 1 is ease, create a Rectangle class. To do this we need the following code stored in a .java file with the same name as the class. In this case Rectangle.java.


public class Rectangle{

}

Well that was super easy. Now let us add the 2 attributes:


public class Rectangle{

	private double length;
	private double width;

}

Ok. That is still easy, but why is there the word “private” there? That is a variable modifier that tells Java what is the working scope of a variable or a method. There are 3 modifiers, private protected and public. Usually attributes of classes are private, at least in the beginning of programming. This is a whole other discussion by itself.

The next thing we need is called a constructor. A constructor is a method that is invoked when to Object is created. This is normally where the attributes are setup. The constructor has to have the same name as the class and does not have a return type like a normal function would have. Here is what our default constructor will look like for Rectangle.


public Rectangle(){
	this.length = 1.0;
	this.width = 1.0;
}

Notice that we used the modifier this to denote the class attribute and not a local variable length. This is not a must, but it will make you life easier and in some cases save you a lot of time figuring out why things are not working like you except. The constructor we have is the empty constructor. It is not a must, like I said. If you do not write a constructor, Java will inherit one from the generic Class definition. That means that nothing will happen beside Java giving your variable an address.

Moving forward (or downward) in our list we need a getter and setter for each attribute. Remember a few paragraphs ago I mentioned something about data integrity? This is where the getter and setters com in to play. They act as a buffer between the user and the values of the attributes. In the case of getters they just return the value (normally). In the case of setters we can modify the actual attribute only if it is an acceptable value. In our case we can write our setters such that if the values are less than 1.0 or more than 10.0 the value of the Object is not set. Let’s take a look:

Here are our getters:


public double getLength(){
	return this.length;
}

public double getWidth(){
	return this.width;
}

And here are the setters:


public void setLength(double length){
	if((length >= 1.0) && (length <= 10.0))           	this.length = length; } public void setWidth(double width){ 	if((width >= 1.0) && (width <= 10.0))
          	this.width = width;
}

That was not so bad, was it? Before we move on to testing we have to complete 1 more task, writing a method for computing perimeter and area. That should be really straight forward.


public double perimeter(){
	return 2 * (this.length + this.width);
}

public double area(){
	return this.getLength() * this.getWidth();
}

You will notice that in the perimeter method we used this to access the variables, while in the area method we used the getters. Both styles are ok and will yield the same results. This was done for educational purposes only.

So now we are done with our class and can move on to testing. Wrong! I highly recommend you take the time to write a debug toString() method. Why? you will thank me later. Here is my toString() for Rectangle:


public String toString(){
	return "Length: " + this.length +"\tWidth: " + this.width;
}

It may seem simple, but later when you are dealing with multiple classes, it is nice to just be able to print them. Let us try to actually use our class. We are going to use a Scanner for user input and standard user output (terminal screen). Here is a simple Main I put together. If you find it useful here is a link to Java Rectangle Class.


public static void main (String[] args)
{

	Scanner userInput = new Scanner(System.in);
	Rectangle r = new Rectangle();

	System.out.print("Enter a length >>> ");
	r.setLength(userInput.nextDouble());

	System.out.print("Enter a width >>> ");
	r.setWidth(userInput.nextDouble());

	System.out.println("The Rectangle with the following attributes: \n" + r);
	System.out.println("Has perimeter is:  " + r.perimeter() + " and area is:  " + r.area());

}

And the output:

wpid-java_rectangle_output-2013-10-18-00-49.png

That is all. Easy isn’t it?