Jump to content

  • Curse Sites
Become a Premium Member! Help
Latest News Article

Question about Java?


  • Please log in to reply
19 replies to this topic

#1

VoteLobster

Posted 20 February 2012 - 09:23 PM

I'm working on a little program that calculates the area of a triangle, rectangle, and circle in Java. I separated the three into separate classes:
(triangle)
import java.io.PrintStream;
import java.util.Scanner;

import java.util.Scanner;

public class TriangleArea 
{

	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args)
	{
		System.out.println("Enter the base length of the triangle:");
		double base = sc.nextDouble();
		
		System.out.print("Enter the height length of the triangle:");
		double height = sc.nextDouble();
		
		double preCalculation = base * height;
		
		double Area = preCalculation / 2.0;
				System.out.println("The Area of your triangle is: " +Area);
		
	}
}

(rectangle)
import java.io.PrintStream; 
import java.util.Scanner;
public class Rectangle 
{
	
	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args)
	{
		System.out.println("Enter one of the side lengths:");
		double length1 = sc.nextDouble();
		
		System.out.println("Enter the other side length");
		double length2 = sc.nextDouble();
		
		double Area = length1 * length2;
				
				System.out.println("The area of your rectangle is: " +Area);
		
				
		
		
	}
	
	
	

}

(and circle)
import java.io.PrintStream;
import java.util.Scanner;

public class CircleArea {

	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args)
	{
		System.out.println("Enter the radius of your circle:");
		double radius = sc.nextDouble();
		
		double Area = 3.1415926535 * radius * radius;
		
		System.out.println("The area of your circle is: " +Area);
		
				
	
	

	}

}


I need a way to have a class determine which other class to use. I have this so far:

import java.io.PrintStream;
import java.util.Scanner;
public class MainClass {

	public static void main(String[] args) {
		System.out.println("Would you like to calculate the area of a Triangle, Rectangle, or Circle?:");
		
		

	}

}
I want to have it ask you which one, and by text input (triangle, rectangle, or circle) I need a way to let it know which class to run.
But where do I go from there? I'm confused. I keep getting bracket errors.
Posted Image

Register or log in to remove.

#2

Taizz
    Taizz

    Void Walker

  • Members
  • 1751 posts
  • Location: England
  • Minecraft: Taizzz

Posted 20 February 2012 - 09:29 PM

Well, I guess you would start off with an 'if' statement, but I'm not too sure either what to do from there... :/

Have I helped you? If I have why not help me back and hit the Posted Image down below? :D


#3

VoteLobster

Posted 20 February 2012 - 09:30 PM

I tried to use
if(args[0].equals("Triangle")) 
But I couldn't quite get it to work.
Posted Image

#4

Xaanos
    Xaanos

    Creeper Destroyer

  • Curse Premium
  • Curse Premium
  • 5792 posts
  • Location: Kansas
  • Minecraft: Devilblade

Posted 20 February 2012 - 09:31 PM

Make one class then make a method  one that gets the input and then you just need an If statement in it. Put the rest in there own methods in the same class.

I wont give you the code that would make it too easy.

But have the main method have it output press 1 for triangle 2 for rectangle or 3 for circle.

Then have an if else for 1 2 and 3 then in the else make it output invalid number and call the main method or you could stick it all in a giant loop.

#5

VoteLobster

Posted 20 February 2012 - 09:32 PM

I just started learning java... I need the code  :huh:

And so it doesn't seem to lazy, it wouldn't hurt if you put some explanation of it...

import java.io.PrintStream;
import java.util.Scanner;
public class MainClass {

	public static void main(String[] args) {
		System.out.println("Press 1 for triangle, 2 for rectangle, and 3 for circle:");
		
		

	}

}

and then?
Posted Image

#6

orbit79
    orbit79

    Carpenter

  • Members
  • 60 posts
  • Location: Canberra, Australia
  • Minecraft: orbit79
  • Xbox:PaleBlueDot79

Posted 20 February 2012 - 09:35 PM

This seems like a good candidate for the use of inheritance. The following is probably how I'd look to setup such a program. If you'd like further description just let me know.

Superclasses

Shape

Subclasses

Triangle
Rectangle
Circle

Other Classes

ShapeArea (what you've called MainClass, I just don't like that name, for reasons I won't go into, unless you really want me to)

#7

VoteLobster

Posted 20 February 2012 - 09:36 PM

How do I make the classes Superclasses or Subclasses? I'm using Eclipse if that helps.
And what is the superclass Shape?
Posted Image

#8

Xaanos
    Xaanos

    Creeper Destroyer

  • Curse Premium
  • Curse Premium
  • 5792 posts
  • Location: Kansas
  • Minecraft: Devilblade

Posted 20 February 2012 - 09:49 PM

View PostVoteLobster, on 20 February 2012 - 09:32 PM, said:

I just started learning java... I need the code  :huh:

And so it doesn't seem to lazy, it wouldn't hurt if you put some explanation of it...

If you just copy paste you don't learn ill put some code but I will tell you how to do it.


Ok create 1 class you don't need a new class for every thing.

Have it print Please type 1 for Triangle 2 for circle 3 rectangle.

Then your main method in it put a scanner to input into a byte

Byte is primitive data type.

just call it typeinput

Then make If else statements.

Use == to see if something is = if you just put = you are telling it to be equal to it.

if (typeinput == 1){
circle();
}

if else (typeinput == 2){
square();

}
if else (typeinput == 3){
rectangle();

}



That would be put in the main method.

Now after that you would create a method called circle.
public void circle(){





}



Do that for circle triangle and square and copy and paste the code you did earlier out of the circle class for the circle method etc.

#9

orbit79
    orbit79

    Carpenter

  • Members
  • 60 posts
  • Location: Canberra, Australia
  • Minecraft: orbit79
  • Xbox:PaleBlueDot79

Posted 20 February 2012 - 09:52 PM

When I started posting my reply there hadn't been any responses yet. As such I wasn't aware that you were brand new to java. Possibly my suggestion is too complicated for you at this stage. I suggest you follow Xaanos' approach and see how you go. People are going to be reluctant just to give you code for a couple of reasons: 1. You learn more in general by trying to code it yourself. If after a really good effort you still cannot do it, then an example can help. 2. People don't want to do other people's homework for them.

I think you should give Xaanos' method a fair shot. If you can get it working, or can show that you've given it a fair shot, I will show you how to implement it using inheritance, and explain it to the best of my ability.

#10

VoteLobster

Posted 20 February 2012 - 10:08 PM

(I do agree that it's not great to just copy-paste the code; That's why I asked for explanation. I gave a bunch of different suggestions a fair shot, but I couldn't get them to work)

I checked the classes for the individual shapes I made earlier; I put static Scanner ___ = new Scanner(System.in); in the same place, but at the If line it recognizes 'typeinput' but still gives me an error

import java.util.Scanner;
public class Main {
	static Scanner typeinput = new Scanner(System.in);

	public static void main(String[] args) {
		System.out.println("Type 1 for triangle, 2 for rectangle, 3 for circle.");
		
		if (typeinput == 1){
			
		}
		

	}

}

Posted Image

#11

orbit79
    orbit79

    Carpenter

  • Members
  • 60 posts
  • Location: Canberra, Australia
  • Minecraft: orbit79
  • Xbox:PaleBlueDot79

Posted 20 February 2012 - 10:48 PM

I have to go to work now but will post an object oriented approach tonight. A quick note, only one class in a java application should have a main method. Having it as you do allows each class to run as a standalone application, but not when merged into a single application. I could be wrong, but I feel you may be confused by object oriented programming concepts. It might be worth taking a procedural approach in this case (as suggested above by Xaanos). What I provide you will be an object oriented approach, which I will attempt to explain.

#12

VoteLobster

Posted 20 February 2012 - 11:00 PM

I understand what you mean. The other day I wrote them all for separate classes; (stupid decision; I got a little ahead of myself there) now to finish I just need to merge them together with ifs and elses.
Posted Image

#13

MrQuizzles
    MrQuizzles

    Retired Staff

  • Retired Staff
  • 4568 posts

Posted 21 February 2012 - 03:10 AM

View PostVoteLobster, on 20 February 2012 - 11:00 PM, said:

(stupid decision; I got a little ahead of myself there)

It's not really that stupid of a decision. As orbit79 said, this is a great place to use polymorphism. You had the right idea, you just didn't quite know what you were doing yet.

this might be a bit out of your league right now, but very quick breakdown of inheritance and polymorphism:

When a class inherits from another class, the class being inherited from is called the 'parent' class, while the class inheriting from the parent is known as the 'child' class. The child class receives all the fields and functions of the base class, which you can then add on to in the class definition.

The relationship between a parent class and a child class is known as an "is a" relationship. Take the example of a parent class "shape" and its child class of "triangle". Triangle inherits from shape, therefore triangle is a shape.


Polymorphism is treating a set of child classes that all inherit from a common parent class as if they were that parent class. Often times, the parent class is abstract, meaning that you cannot ever encounter an instance that is purely that class. If we put this into the perspective of the previous example, if shape was defined as abstract, you will never encounter a object of type shape. You can still encounter triangles, which are shapes, as well as any other class that inherits from the abstract class 'shape', but never shape all by itself.

So if you had an abstract class, shape, with the abstract function getArea(), you could then define a bunch of classes that inherit from your shape class (such as triangle, circle, rectangle, etc.) and override the getArea() function in those classes to do the specific calculation for that particular shape.

What you can then do is tell the class that makes the decision to expect an object of type shape as a parameter to one of its functions and then call the getArea() function. You can then pass it any class that inherits from shape, and the getArea() function that will be called is the function of the child class that was passed to it. It says "give me a shape", you say "here's a triangle", and it's okay with that. It says "give me a shape", you say "here's a circle", and it's fine with that.

#14

VoteLobster

Posted 21 February 2012 - 09:27 PM

So... there would be a 'get area' class, with each of the formulae in it,  and the separate shapes have their own class, such as 'triangleClass'? And that shape class will tell the 'get area' class which formula to use?

From what I understand so far, You would have a Main class. You run it, and it asks you which shape you want. When you give it your input, say, it will go to 'get area' class and that will refer to your shape class (be it triangle) then it performs the calculations, sends it to the main, and spits it out for you? Code wise, not sure how to do that, but kinda makes sense to me. Somewhat.
Posted Image

#15

MrQuizzles
    MrQuizzles

    Retired Staff

  • Retired Staff
  • 4568 posts

Posted 21 February 2012 - 10:25 PM

View PostVoteLobster, on 21 February 2012 - 09:27 PM, said:

So... there would be a 'get area' class, with each of the formulae in it,  and the separate shapes have their own class, such as 'triangleClass'? And that shape class will tell the 'get area' class which formula to use?

No, there'd be a bunch of types of shape, and each type would have its own class. Each of those classes will have a 'get area' function that overrides the one declared in the parent 'shape' class.

Each of the shapes will know how to calculate their own area. Polymorphism allows us to tell those shapes to use that function even if we don't know exactly what kind of shape it is.

It'd look something like this:

public abstract class shape
{
	private ArrayList<double> points;//define the polygon's points

	public shape()
	{
	}

	abstract public double getArea();

	//put accessors and mutators in, of course
}


//------------pretend this is a different file

public class triangle extends shape
{
	public triangle()
	{
	}

	@Override
	public double getArea()
	{
		 //put the code to calculate area for a triangle here
	}

	//put accessors and mutators in, of course
}

//--------------pretend this is a different file again

public class circle extends shape
{
	private double radius;

	public circle()
	{
	}

	@Override
	public double getArea()
	{
		 //put the code to calculate area for a circle here
	}

	//put accessors and mutators in, of course
}

So with that, you could then do something like this:

	shape roundThing = new Circle();
	roundThing.setRadius(5);

	double roundArea = roundThing.getArea();//will give you the area of the circle

So even though roundThing is a shape, you can put a circle in its place because a circle is a shape. Then, when you use the getArea function, it gives you the correct area for the specific shape you put in it.

#16

orbit79
    orbit79

    Carpenter

  • Members
  • 60 posts
  • Location: Canberra, Australia
  • Minecraft: orbit79
  • Xbox:PaleBlueDot79

Posted 21 February 2012 - 11:09 PM

Sorry for delay, didn't end up getting home until 11 pm last night so didn't get to code it until this morning. This is only one way of coding it, there are almost always several approaches that can be taken to solve any given problem. I believe I've done it in a manner which I've done it should make it reasonably readable. I have attempted to include some of the core concepts for you. I understand that this doesn't directly answer your original question, however I think it could help you OOP skills nonetheless. I haven't included any inputing or decision making based on input, due to the fact the I was trying to keep it as simple as possible, and in part because judging from your posts I think you have the skills to do so yourself (now that the structure is a bit more sound). It could be a good exercise. In any case, feel free to ask as many questions as you like. MrQuizzle's post might make my code a little easier to understand too, so I suggest you read them in unison.

I hope that helps, thanks.

PS. I have included the colour stuff to demonstrate how a subclass will call the method from the superclass in the event that a copy within the subclass is not defined.

Shape.java
public abstract class Shape { //This is an abstract class, meaning it never directly instantiated. Only subclass/child classes can of this class can be instantiated
	protected double area;
	private String colour;
	
	//No constructor, so default empty constructor will be used
	
	public double calcArea() { //This will never actually be called, but to override it in subclasses/child classes we need to have it defined here
		return 0;
	}
	
	public String getColour() { //When no method of the same name is found in a subclass/child class, java will look to this (the superclass/parent class) and run this one
		return colour.toString();
	}

	public void setColour(String colour) {
		this.colour = colour;
	}	
}

Rectangle.java
public class Rectangle extends Shape { 
	private double length;
	private double breadth;
	
	//constructor
	public Rectangle(double length, double breadth) {
		this.length = length;
		this.breadth = breadth;
	}
	
	public double calcArea() { //Override calcArea method
		return length * breadth;
	} 
}

Triangle.java
public class Triangle extends Shape
{	
	private double base;
	private double height;
	
	//constructor
	public Triangle(double base, double height) {
		this.base = base;
		this.height = height;
		area = 0;
	}
	
	public double calcArea() { //Override calArea method
		return (base * height) / 2;
	}
}

Circle
public class Triangle extends Shape
{	
	private double base;
	private double height;
	
	//constructor
	public Triangle(double base, double height) {
		this.base = base;
		this.height = height;
		area = 0;
	}
	
	public double calcArea() { //Override calArea method
		return (base * height) / 2;
	}
}

AreaCalculator.java
public class AreaCalculator {
	public static void main(String[] args) {	   
		Shape shape;
		
		shape = new Rectangle(10, 5);
		shape.setColour("Red");
		
		System.out.println("RECTANGLE");
		System.out.println("*********");
		
		System.out.println("Area: " + shape.calcArea());
		System.out.println("Colour: " + shape.getColour() + "\n");
		
		shape = new Triangle(10, 5);
		shape.setColour("Green");
		
		System.out.println("TRIANGLE");
		System.out.println("********");
		
		System.out.println("Area: " + shape.calcArea());
		System.out.println("Colour: " + shape.getColour() + "\n");	 
		
		shape = new Circle(5);
		shape.setColour("Blue");

		System.out.println("CIRCLE");
		System.out.println("******");

		System.out.println("Area: " + shape.calcArea());
		System.out.println("Colour: " + shape.getColour() + "\n");
	}
}


#17

VoteLobster

Posted 22 February 2012 - 02:07 AM

Questions:

1- With the 'public String getColor' command, I see that you set the colors for the shapes in AreaCalculator.java. From what I see, is this just another way of labeling the different shapes, and the color refers back to the AreaCalculator class to know which Triangle/Rectangle/Circle class to use? Not have to label them individually?

2-Can you explain what the AreaCalculator class and Shape class are doing, in a nutshell?

By the way, I used completely different calculation codes for the shapes, but I don't imagine that would affect it much?

3-What exactly is a Double? An integer value?

Also, I talked to my friend about it today. He said to do this: (this was for merging all of the shape classes into one big class)
Public class Main{
Static int textinput = new Scanner(system.in)

then from there it goes into
System.out.println("1 for triangle, 2 for rectangle, 3 for circle");
if(textinput .equals 1){
//then from there it goes into the calculator} 

at the end he said to put a 'return;' .
Is a return; just for ending if statements? Return to the main code, per say?

I also tried this but when I ran it, it didn't ask for text-input.
Posted Image

#18

MrQuizzles
    MrQuizzles

    Retired Staff

  • Retired Staff
  • 4568 posts

Posted 22 February 2012 - 04:53 AM

1. Things don't 'refer back to' other things in these programs. The main method in the AreaCalculator class creates a bunch of shapes, each one with a color. One shape is a rectangle, another is a triangle, and the last is a circle. These shapes know which shapes they are. The AreaCalculator class doesn't know and doesn't care about which shapes they are. It just cares that they are shapes, and it will treat them as such. No more, no less.

So when the AreaCalculator class tells each shape to use its getArea() function, each shape will call its own getArea function. The functions defined in the child classes are used because those functions override the getArea function found in the shape class. They are all shapes, so they each have a getArea function, but each one has its own specific method of finding its area.

On the other hand, when the AreaCalculator class tells each shape to use its getColor() function, each shape will use the getColor function from the shape class. In this case, the function from the shape class is used because none of the child classes have overridden it with their own functions. Though they may be different from the base shape class in many ways, they are all still shapes.

3. A double is a type of floating point value. It's called a double because it uses twice as much memory as a float. It honestly doesn't make much of a difference these days, but it did some 20-30 years ago. Stick to using doubles unless you need to make many millions of them and memory use actually does become an issue.

4. The return statement informs the program to exit the function and send back a particular value. This value must be of the type laid out in the function's declaration. When you see a function like this:

public int getInteger()

Then that function must return an integer value.

In Java and many other languages, the function call itself can be treated as the type it returns. This is true to the point that you can chain function calls based upon what each function returns.


ArrayList<int> thingy = new ArrayList();

if(thingy.toString.matches("woop"))
{
   // do something meaningless here
}


So here I'm calling the .toString() function, which is common to all objects in the Java libraries. Since it returns a String, I'm capable of calling the .matches() function, which is a member function of the String class, on that function call.

Putting a return statement in the main method causes the program to exit.

Also note that I keep using the word "function" even though I should technically be saying "method". A method is a function that is part of a class, a "member function" if you will. In Java, functions that aren't members of classes don't exist, so they're technically all methods.

#19

VoteLobster

Posted 24 February 2012 - 12:29 PM

So now I more understand what a method is; so a method is a function/ within the Main method that is run with the rest of the class? Do they only exist in Main classes? or are they put in other classes?

So just making sure. A double is a value (does it have to be an integer?) that is used with the class to perform a function?
Posted Image

#20

BC_Programming
  • Location: Nanaimo, BC
  • Minecraft: BC_Programming

Posted 24 February 2012 - 01:57 PM

I started writing a ridiculously over-engineered solution (using reflection to find all the types that implement the abstract base class and prompting for each field before calling the method to calculate area).

About half-way through I remembered that I hated java. Or perhaps hatred was renewed when, instead of being able to follow a sane approach and, you know, be able to enumerate Types/classes in a package, I was forced to essentially write a god damned ClassLoader. But I digress.

That, and the result would have in no way helped the OP....

Quote

So now I more understand what a method is; so a method is a function/ within the Main method that is run with the rest of the class? Do they only exist in Main classes? or are they put in other classes?
A method is a function on an object. To calculate the area of a shape, for example, you'd call a method. When you write to the output stream (using system.out.println) you are calling the println method of the OutputStream class. When you read a double from the Scanner, you are calling the getDouble() method.

You've got two types of methods, basically (well, in java, let's not complicate things). You have methods that belong to the object instance and methods that belong to the object class. A Class essentially defines the template for each instance. The build in "String" type is a class, and you can call "String.ValueOf" and get the string representation of a value. there you aren't accessing a string, but rather the class itself- you don't need an instance. Whereas if you have a string variable, it is an "instance" of a string and any and all strings will have the instance methods of string.

The "Main" method is only special by convention; by convention the way a Java class is "started" is by the java class loader loading up the class, finding the Main Method, and invoking it. it is static because by virtue it doesn't need to have a loaded instance of the class it is contained in, and if the routine needs an instance it can create one anyway.


Quote

So just making sure. A double is a value (does it have to be an integer?) that is used with the class to perform a function?
double is a data type. http://docs.oracle.c.../datatypes.html



The return statement returns to the caller. In the case of the Main method, this will return to the Java class loader, or whatever loaded up your program. What it is doesn't really matter, but basically when you return from the main method your program is finished. Within other methods, it returns to whatever called it.