3 Replies - 275 Views - Last Post: 07 May 2012 - 12:01 PM Rate Topic: -----

#1 Cure4Karma  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 15-October 09

How would i go about making this object Orientated?

Posted 07 May 2012 - 05:38 AM

I have been reading the book Java Early Objects 4th Edition and I don't understand the whole Object orientated perspective of java. I know that its a standard in java programming, but the book doesn't explain it all that well.


import java.util.Scanner;
import java.lang.String;

public class Quiz
{
	
	//This method simply prints the user's input to the console.
	public static void printResults(String userInput[]){
		System.out.println("\nQuestion No.\tUser Input");
		for (int i = 0; i < userInput.length; i++){
			System.out.println((i + 1) + ".\t\t" + userInput[i]);
		}  
		
	}   // end of method printResults(...)
	
	 /**
	 *  This method prints the correct answers and the user's input to the console. 
	 */
	public static void printResults(String correctAnswers[], String userInput[]){
		System.out.println("Question No.\tCorrect answer\tUser Input");
		for (int i = 0; i < correctAnswers.length; i++){
			System.out.println((i + 1) + ".\t\t" + correctAnswers[i] + "\t\t" + userInput[i]);
		}   
		
	}   // end of method printResults(...)
		

	  //This overloaded method prints the correct answers
	public static void printResults(String correctAnswers[], String userInput[], int numberCorrectAnswers){
		System.out.println("\nQuestion No.\tCorrect answer\tUser Input");
		for (int i = 0; i < correctAnswers.length; i++){
			System.out.println((i + 1) + ".\t\t" + correctAnswers[i] + "\t\t" + userInput[i]);
		}  
		System.out.println("\nNumber of questions answered correctly: " + numberCorrectAnswers);

	} 
	

	 /**
	 *  This method calculates the number of correct answers in-putted by
	 *  the user and returns it to the calling method.
	 */
	
	public static int compareResults(String correctAnswers[], String userInput[]){
		
		int numberCorrectAnswers = 0;
		
		
		for(int i = 0; i < correctAnswers.length; i++){
			if (correctAnswers[i].equals(userInput[i])){
				numberCorrectAnswers++;
			}
		} 
		
		return (numberCorrectAnswers);
	   
		
		
	} // end compare results
	
	public static void main(String args[]){
		int numQ = 15;  //Number of questions, increase if new questions added
		double perc = .6; //percent needed to pass (60%)
		final String correctAnswers[] = new String[15];
		
		correctAnswers[0] = "B";
		correctAnswers[1] = "C";
		correctAnswers[2] = "B";
		correctAnswers[3] = "C";
		correctAnswers[4] = "A";
		correctAnswers[5] = "B";
		correctAnswers[6] = "A";
		correctAnswers[7] = "C";
		correctAnswers[8] = "A";
		correctAnswers[9] = "A";
		correctAnswers[10] = "A";
		correctAnswers[11] = "C";
		correctAnswers[12] = "C";
		correctAnswers[13] = "A";
		correctAnswers[14] = "A";
		
		Scanner myScanner = new Scanner(System.in);
		
		String userInput[] = new String[15];
		
		final String questions[] = new String[15];
		
		questions[0] = "On a standard traffic light, is the green on the top or bottom?\n \n A - Top \n B - Bottom \n C - Middle ";
		questions[1] = "How many states are there? \n \n A - 48 \n B - 52 \n C - 50 \n D - 51 ";
		questions[2] = "How many inches in a foot?  ------- \n \n A - 24 \n B - 12 \n C - 36 \n D - A million and one ";
		questions[3] = "How many metres in a mile?  ------- \n \n A - 2040m \n B - 1212m \n C - 1609m \n D - 1440m ";
		questions[4] = "In which hand is the Statue of Liberty's torch? \n \n A - Right \n B - Left \n C - No Torch ";
		questions[5] = "What two letters don't appear on the telephone dial? \n \n A - R, S \n B - Q, Z \n C - X, Y \n D - Z, Q ";
		questions[6] = "What two numbers on the telephone dial don't have letters by them? \n \n A - 1, 0 \n B - 8, 9 \n C - 2, 0 \n D - 1, 9 ";
		questions[7] = "How many matches are in a standard pack?  \n \n A - 15 \n B - 25 \n C - 20 \n D - 30 ";
		questions[8] = "On the United States flag is the top stripe red or white? \n \n A - Red \n B - White ";
		questions[9] = "Which way do fans rotate as you look at them?  \n \n A - Clockwise \n B - Counter-Clockwise ";
		questions[10] = "Whose face is on a dime?  \n \n A - Roosevelt  \n B - Washington \n C - Bush \n D - Carter ";
		questions[11] = "How many sides does a stop sign have?  \n \n A - 6 \n B - 7 \n C - 8 \n D - 9 ";
		questions[12] = "How many hot dog buns are in a standard package?  \n \n A - 6 \n B - 10 \n C - 8 \n D - 12 ";
		questions[13] = "On the back of a $1 bill, what is in the center?  \n \n A - 1 \n B - Pyramid \n C - A President \n D - George Washington ";
		questions[14] = "How many curves are there in the standard paper clip?  \n \n A - 3 \n B - 4 \n C - 5 \n D - 2 ";
		
		
		
		System.out.println("Welcome to the quiz.\n");
		System.out.println("Please choose the correct responses.\n");
		
			  
		for (int i = 0; i < numQ; i++){
			
			
			
			System.out.print(" \nPlease enter answer to question " + (i + 1) + " >>  \n\n" + questions[i]);
			userInput[i] = myScanner.nextLine();
			userInput[i] = userInput[i].toUpperCase();

			// Perform some error checking here
			
			if	
			
				(userInput[i].equals("A") || userInput[i].equals("B") || userInput[i].equals("C") || userInput[i].equals("D")); 
			   // Do nothing;
			
			else userInput[i] = "X"; 
			
			
		}  
		
		int numberCorrectAnswers = compareResults(correctAnswers, userInput);
		
		int numberIncorrectAnswers = (numQ - numberCorrectAnswers);
		
		printResults(correctAnswers, userInput, numberCorrectAnswers);
		
		System.out.println("\nYou got " + numberIncorrectAnswers + " answers incorrect.\n");
		
		System.out.println(100 * numberCorrectAnswers/numQ + "% Correct");
		
		if (numberCorrectAnswers > numQ*perc)
		{			System.out.println("\nWell done you passed the quiz");
			}
		else
		{
			System.out.println("\nSorry, you have failed the quiz.");
			}
	}
	
}




Is This A Good Question/Topic? 0
  • +

Replies To: How would i go about making this object Orientated?

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5522
  • View blog
  • Posts: 11,830
  • Joined: 02-June 10

Re: How would i go about making this object Orientated?

Posted 07 May 2012 - 08:10 AM

Think of objects in coding just as you would objects in the real world.

A Dodge Ram is an object.
It is made up of smaller objects: Engine, doors, tires
Each of those is made up of smaller objects: Bolts, pistons, etc.

Objects in coding can inherit from each other, usually from the general to the specific.

  • Class vehicle
    • Class truck : vehicle
      • Class Ram : Truck
        • class 2500FWD : Ram


A class is the blueprint for instanciating (making an instance of) the object.

DodgeRam is a class describing how to make an instance, but itself is not an actual thing you can interact with.

myDodgeRam is an instance of a the class DodgeRam

I can do things with the object instance myDodgeRam

myDodgeRam.SerialNumber = 123456789;
myDodgeRam.FillUpTank();
float fuelLevel = myDodgeRam.FuelTankPercentageFull;
if (myDodgeRam.IsReady) myDodgeRam.StartEngine();


Anything defined in the base class is available to a child.

class truck : vehicle
{

    public float FuelTankPercentageFull
    {
       get; set;
    }
}

class DodgeRam : truck
{
    // I don't have to define a FuelTankPercentageFull here because I inherit it from my parent
}


Methods defined as virtual in the base class can be overridden by the child class (at least in .NET languages like C#). This is often to account for more specific needs.

class truck : vehicle
{

    public virtual bool StartEngine()
    {
       // Do something to start the engine
       return true; // No checks or requirements
    }
}

class DodgeRam : truck
{
    public override bool StartEngine()
    {
        // Do a safety check first
        if (IsSeatBeltsEngaged && IsFootOnBrake)
        { 
            return true;
        }
        return false;
    }
}


You can even have a child class call the base classes methods which is often the smart way to go.

class truck : vehicle
{

    public virtual bool StartEngine()
    {
       // Notice there are no safety checks before trying to start up.
       try
       {
          // Do something to start the engine
          return true; // because we succeeded
       }
       catch(exception error)
       {
           return false; // because there was an error
       }
    }
}

class DodgeRam : truck
{
    public override bool StartEngine()
    {
        // Do a safety check first
        if (IsSeatBeltsEngaged && IsFootOnBrake)
        { 
            return base.StartEngine();
            // Now all the electrical work is in the base class
            // and not repeated in every child.
        }
    }
}

Was This Post Helpful? 2
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8332
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: How would i go about making this object Orientated?

Posted 07 May 2012 - 11:39 AM

A lot a C++ in that code

class truck : vahicule

is

class Truck extends Vehicule

in Java

there is no "virtual" in Java

"bool" are "boolean" in Java

but the concept remain the same. And you wont go OO at all if your methods are declare static
Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5522
  • View blog
  • Posts: 11,830
  • Joined: 02-June 10

Re: How would i go about making this object Orientated?

Posted 07 May 2012 - 12:01 PM

View Postpbl, on 07 May 2012 - 12:39 PM, said:

A lot a C++ in that code
bool" are "boolean" in Java
...
but the concept remain the same. And you wont go OO at all if your methods are declare static


It was meant to be a conceptual example. Something to provide an analogy to most westerners who have cars. There is something about car metaphors that people click with. They use cars every day. They aren't afraid of them. They grok.

Yes it is more C# oriented. But it wasn't meant to be a language specific tutorial. People studying a specific language should have a book or tutorial in front of them already for the exact syntax. This is just something to get the overall concepts into people's heads in a way they would accept and not be so afraid of.

This post has been edited by tlhIn`toq: 07 May 2012 - 12:02 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1