I have recently started with programming. So far I have learned basics and now its time for OOP and so i have some questions as im building basic programs to just understand principals and link to way I would use it in practical ways.
So I am making simple triangle program in Java, so far it calculates perimeter (later will ad other shapes and other parameters), I hit the wall where I want to add Triangle existence (as side can't be negative) and also Id like to allow user input. Thing is i don't know where to put code and how to refer to class. Linear (non OOP) way it is simple, but how its done in OOP, do i have to make another class or in Triangle class via methods?
my code:
public class Trissturis {
private int sideA, sideB, sideC;
private double perimeter;
public Trissturis(int a, int b, int c) {
sideA = a;
sideB = b;
sideC = c;
}
public double getPerimeter() {
return sideA + sideB + sideC;
}
}
public class TestTri {
public static void main(String[] args) {
Trissturis t1 = new Trissturis(10, 20, 30);
System.out.println("perimeter is " + t1.getPerimeter());
Trissturis t2 = new Trissturis(-1, 20, 30);
}
}
To validate the triangle you have to check that all sides have a length greater than zero, and that no side is longer than the sum of the other two. An method that would accomplish this is:
public boolean isValid(){
return (sideA>0)&&(sideB>0)&&(sideC>0)&&(sideA+sideB>sideC)&&(sideA+sideC>sideB)&&(sideC+sideB>sideA);
}
For the user to input values, it is better to have separate user-interface classes. If this will be a desktop application, you could use some of the Swing classes, for example (although there are alternatives).
interface TriangleFactory {
Triangle create();
}
class ConsoleTriangleFactory implements TriangleFactory {
#Override
Triangle create() {
// read perimeter from console here with some nice prompt
// check that every side is > 0,
// if it's not a number or less than 0 - then do some alert
}
}
Your code to check that the triangle is constructed correctly (with non-negative values, etc) belongs in the Triangle class.
Code to take user input can go in main() in your Test for a small program, but could go in a separate UI namespace for a larger application.
hth
Related
This code does not run when I try to compile it, I am sure it is because I
defined my function/method incorrectly, so it would be much appreciated if
someone can correct my code and also tell me what is wrong with it.
I know C++ so I tried to define the function like how I would define it
normally in Cpp but with a few tweaks. I really don't know what I am doing
right now.
class Calculator {
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
final float k = 5 / 9;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
public float Converter(float Farenheit) {
return 5 / 9 * (Farenheit - 32);
}
}
}
So the comments noted the key issues. The method cannot be within main. 5/9=0 in Java. Here is a little program I just checked on jdoodle.com. It does what you said in what might be typical Java style (though for sure there are possible improvements and things with which to quibble). For learning Java (which is not the same as for experienced users for development), bluej is an interesting IDE with which to start (specifically because it doesn't do all the work for you). But StackOverflow does not want judgment questions like that, so ignore if you wish.
public class Calculator {
public double converter(double Farenheit) {// convention converter lower case because not a class name
return 5.0 / 9 * (Farenheit - 32); //note 5.0 ensures real number arithmetic, not integer
}
public static void main(String[] arguments) {
Calculator calculator = new Calculator();// make a calculator object, alternative would be to declare converter static
double Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
calculator.converter(Farenheit));
}
}
Your method public float Converter(float Farenheit) is written inside main method . This is not allowed in JAVA . You can however write a anonymous class inside a method and calls its methods .
The correct code is :
class Calculator {
private static final float k = 5.0f / 9;
public static void main(String[] arguments) {
float Celcius;
float Farenheit = 32;
System.out.println("This is the temperature in degrees celsius: " +
Converter(Farenheit));
}
public static float Converter(float Farenheit) {
return k * (Farenheit - 32);
}
}
Please note I have modified Converter method to a static one . We cannot call non static methods from static context in JAVA(as main is static here) . If Converter would have been non static then we would have to create an object of the Calculator class.
Calculator c = new Calculator();
c.Converter(Fahrenheit);
You can declare k as class level variable if it is to be used across multiple methods and has a constant value .
private static final float k = 5.0f / 9;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
What's wrong with my code ? Why it is not calculating the area of
cirlce correctly in case of circle as a shape? Every time it is
calculating the area of circle equals to 0.Rest of the code is working
fine.
package constructor;
import java.util.Scanner;
class input{
float c_area;
int s_area,r_area;
input(int side1,String type)
{
if(type.equals("circle"))
{
c_area=3.14f*side1*side1;
}
else{
s_area=side1*side1;
}
}
input(int l,int b){
r_area=l*b;
}
void area(String select){
if(select.equals("cirlce"))
{
System.out.println("Area is: "+c_area);
}
else if(select.equals("square")){
System.out.println("Area is: "+s_area);
}
else
{
System.out.println("Area is:"+r_area);
}
}
};
public class shape {
public static void main(String[] args) {
String name;
char ch;
Scanner obj=new Scanner(System.in);
do{
System.out.print("ENTER THE SHAPE TYPE:");
name=obj.next();
if(name.equals("circle"))
{
int radius;
System.out.print("Enter the radius: ");
radius=obj.nextInt();
input a=new input(radius,name);
a.area(name);
}
else if(name.equals("rectangle"))
{
int len,bre;
System.out.print("Enter LENGTH & BREADTH: ");
len=obj.nextInt();
bre=obj.nextInt();
input x=new input(len,bre);
x.area(name);
}
else if(name.equals("square"))
{
int side;
System.out.print("Enter side: ");
side=obj.nextInt();
input x=new input(side,name);
x.area(name);
}
System.out.println("continue: Y or N:");
ch=obj.next().charAt(0);
}while(ch=='y' || ch=='Y');
}
}
What's wrong with my code ? Why it is not calculating the area of
cirlce correctly in case of circle as a shape? Every time it is
calculating the area of circle equals to 0.Rest of the code is working
fine.
The problem is with this piece of code in your input class:
if(type.equals("circle"))
{float c_area;
c_area=3.14f*side1*side1;
}
you are declaring c_area inside if making it local variable and not instance variable, Instead try this
if(type.equals("circle"))
{
this.c_area=3.14f*side1*side1;
}
Hope it helps..
Fist of all it would be better for you to Use "Math.PI" intead of just taking 3.14f it´s more accurate;
In my Oppinoin you should use a static Method to calculate the "c_area" (with the Parametes (radius, Type) and imedietey return that.
I don't see needs to Create an Object so you could delete your Constructor (cause it isn´t needed to work with this Object later.
If this is your whole coode I woult personally just create an Method to calculate the area.. and just don't use another class
he he program is perfectly fine and there is no coding mistake.
only thing is that there is typo in void area(String select){ } method
if(select.equals("cirlce")) should be if(select.equals("circle"))
circle spelling is wrong.
Look at these 2 lines:
float c_area;
c_area=3.14f*side1*side1;
You are declaring a variable named c_area inside the constructor, when you already have a variable named the same way in the class scope declaration. So the compiler ignore the class level variable, and calculates the constructor level variable instead. Of course, the class level variable doesn't change and stays zero by default. Simply remove float c_area; from the constructor and you're good
Notice: if you are new to Java, you should know that it follows certain code conventions. You should name your classes with UpperCase styling, and your variable names should be camelCased
I'm making a Android Application to calculate Math in GPS Format.
Example:
Given
N 48°44.(30x4) E 019°08.[(13x31)+16]
the App calculates it, and result is:
N 48°44.120 E 019°08.419
Is it possible to do this?
I searched for plugins and solutions, but it's all just for math strings like as "14 + 6".
I am assuming you are working in Java as it is tagged in your question.
You could create a new public class for your GPS coordinates, and store the actual value of the coordinate in the lowest division, which according to your example appears to be minutes or seconds. This allows you to store the value as an int or a double with whatever precision you wish. You could then create a set of private and public methods to complete your mathematical operations and others to display your values in the appropriate fashion:
public class GPSCoordinate {
private double verticalcoord;
private double horizontalcoord;
//Constructors
GPSCoordinate(){
setVertical(0);
setHorizontal(0);
}
GPSCoordinate(double vert, double horiz){
setVertical(vert);
setHorizontal(horiz);
}
//Display methods
public String verticalString(){
return ((int)verticalcoord / 60) + "°" + (verticalcoord - ((int)verticalcoord / 60) *60);
}
public String horizontalString(){
return ((int)horizontalcoord / 60) + "°" + (horizontalcoord - ((int)horizontalcoord / 60) *60);
}
//Setting Methods
public void setVertical(double x){
this.verticalcoord = x;
}
public void setHorizontal(double x){
this.horizontalcoord = x;
}
//Math Methods
public void addMinutesVertical(double x){
this.verticalcoord += x;
}
}
This will allow you to initiate an instance in your main code with a given GPS coordinate, and then you can call your math functions on it.
GPSCoordinate coord1 = new GPSCoordinate(567.23, 245);
coord1.addMinutesVertical(50);
coord1.otherMathFunction(50 * 30);
You will, of course, need to refine the above to make it fit your project. If this isn't helpful, please provide more specifics and I'll see if I can think of anything else that might fit what your looking for.
Can't you just substring the whole thing and search for the expression in the brackets? Then it's just a matter of simple calculation. If I understood the question correctly. The gps data doesn't look like an ordinary expression, so you can't appy math() directly.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a class Triangle and a class that extends Triangle that is called IsoscelesRight.
I got this instruction and hint from my teacher to write IsoscelesRight but I'm still unsure as to how to do it.
IsoscelesRight takes just one double value, but sets up the sides so that an isosceles right triangle is formed. Hint: Do this by setting sides a and b to same value, and side c will equal side a times the square root of two. Make sure the constructor appropriately calls super().
public class Triangle
{
private double sideA;
private double sideB;
private double sideC;
public Triangle(double a, double b, double c)
{
sideA = a;
sideB = b;
sideC = c;
}
public double getSideA()
{
return sideA;
}
public double getSideB()
{
return sideB;
}
public double getSideC()
{
return sideC;
}
}
Here's all I have for IsoscelesRight that needs to be changed.
public class IsoscelesRight extends Triangle
{
public IsoscelesRight(double side)
{
super(side, side, side);
}
}
You must be looking for:
public class IsoscelesRight extends Triangle {
public IsoscelesRight(double side) {
super(side, side, Math.sqrt(2) * side);
}
}
I will leave the research as to why to you as this is clearly homework.
Please note that if you just submit this code to your prof you will almost certainly get an f for effort.
A slightly better (and certainly more illuminating) solution would be:
public class Isosceles extends Triangle {
public Isosceles(double side, double hypotenuse) {
super(side, side, hypotenuse);
}
}
public class Right extends Isosceles {
public Right(double side) {
super(side, Math.sqrt(2) * side);
}
}
In any triangle the sides are constrained by Pyphagorean theorem, so if you intend to store sides lenghts you only need to store 2, and the 3rd one (i.e. Hypotenuse) is always computed. This will take less space but take more time to retrieve the hypotenuse as SQRT takes time to compute. So revise your model because it can not just store 3 length for logically-valid triangle (there is no need to take memory for 3 values) without any checks in .ctor.
Just store side A and B, hypotenuse calculate according to formula: A^2 + B^2 = C^2.
If you store all 3 sides then check that values add up according to the formula or your triangle will store logically corrupt data.
If I had been your teacher I would have wanted to at least hear these concerns voiced. The actual class design may be whatever is needed for application - be it speed, performance, logical consistency of data and all combinations of the above.
I'm trying some Java recently and look for some review of my style. If You like to look at this exercise placed in the image, and tell me if my style is good enought? Or maybe it is not good enought, so You can tell me on what aspect I should work more, so You can help me to improve it?
exercise for my question
/*
* File: MathQuiz.java
*
* This program produces Math Quiz.
*/
import acm.program.*;
import acm.util.*;
public class MathQuiz extends ConsoleProgram {
/* Class constants for Quiz settings. */
private static final int CHANCES = 3;
private static final int QUESTIONS = 5;
private static final int MIN = 0;
private static final int MAX = 20;
/* Start program. Number of questions to ask is assigned here. */
public void run() {
println("Welcome to Math Quiz");
while(answered != QUESTIONS) {
produceNumbers();
askForAnswer();
}
println("End of program.");
}
/* Ask for answer, and check them. Number of chances includes
* first one, where user is asked for reply. */
private void askForAnswer() {
int answer = -1;
if(type)
answer = readInt("What is " + x + "+" + y + "?");
else
answer = readInt("What is " + x + "-" + y + "?");
for(int i = 1; i < CHANCES+1; i++) {
if(answer != solution) {
if(i == CHANCES) {
println("No. The answer is " + solution + ".");
break;
}
answer = readInt("That's incorrect - try a different answer: ");
} else {
println("That's the answer!");
break;
}
}
answered++;
}
/* Produces type and two numbers until they qualify. */
private void produceNumbers() {
produceType();
produceFirst();
produceSecond();
if(type)
while(x+y >= MAX) {
produceFirst();
produceSecond();
}
else
while(x-y <= MIN) {
produceFirst();
produceSecond();
}
calculateSolution();
}
/* Calculates equation solution. */
private void calculateSolution() {
if(type) solution = x + y;
else solution = x - y;
}
/* Type of the equation. True is from plus, false is for minus. */
private void produceType() {
type = rgen.nextBoolean();
}
/* Produces first number. */
private void produceFirst() {
x = rgen.nextInt(0, 20);
}
/* Produces second number. */
private void produceSecond() {
y = rgen.nextInt(0, 20);
}
/* Class variables for numbers and type of the equation. */
private static boolean type;
private static int x;
private static int y;
/* Class variables for equation solution. */
private static int solution;
/* Class variable counting number of answered equations,
* so if it reaches number of provided questions, it ends */
private static int answered = 0;
/* Random generator constructor. */
RandomGenerator rgen = new RandomGenerator();
}
One thing I noticed was that all of your methods take no parameters and return void.
I think it would be clearer if you use method parameters and return values to show the flow of data through your program instead of using the object's state to store everything.
There are a few things you should do differently, and a couple you could do differently.
The things you should do differently:
Keep all fields together.
static fields should always be in THIS_FORM
you've used the static modifier for what clearly look like instance fields. (type,x,y,solution, answered). This means you can only ever run one MathsQuiz at a time per JVM. Not a big deal in this case, but will cause problems for more complex programs.
produceFirst and produceSecond use hardcoded parameters to nextInt rather than using MAX and MIN as provided by the class
There is no apparent need for answered to be a field. It could easily be a local variable in run.
Things you should do differently:
There is a small possibility (however tiny), that produceNumbers might not end. Instead of producing two random numbers and hoping they work. Produce one random number and then constrain the second so that a solution will always be formed. eg. say we are doing and addition and x is 6 and max is 20. We know that y cannot be larger than 14. So instead of trying nextInt(0,20), you could do nextInt(0,14) and be assured that you would get a feasible question.
For loop isn't really the right construct for askForAnswer as the desired behaviour is to ask for an answer CHANCES number of times or until a correct answer is received, whichever comes first. A for loop is usually used when you wish to do something a set number of times. Indeed the while loop in run is a good candidate for a for loop. A sample while loop might look like:
int i = 1;
boolean correct = (solution == readInt("What is " + x + "+" + y + "?"));
while (i < CHANCES && !correct) {
correct = (solution == readInt("Wrong, try again."));
i++;
}
if (correct) {
println("Well done!");
} else {
println("Nope, the answer is: "+solution);
}
Looks like a very clean program style. I would move all variables to the top instead of having some at the bottom, but other than that it is very readable.
Here is something I'd improve: the boolean type that is used to indicate whether we have an addition or subtraction:
private void produceType() {
type = rgen.nextBoolean();
}
produceType tells, that something is generated and I'd expect something to be returned. And I'd define enums to represent the type of the quiz. Here's my suggestion:
private QuizType produceType() {
boolean type = rgen.nextBoolean();
if (type == true)
return QuizType.PLUS;
else
return QuizType.MINUS;
}
The enum is defined like this:
public enum QuizType { PLUS, MINUS }
Almost good I have only a few improvements:
variables moves to the top
Inside produceNumbers and your while you have small repeat. I recommend refactor this
Small advice: Code should be like books - easy readable - in your run() method firstly you call produceNumber and then askForAnswer. So it will be better if in your code you will have the same order in definitions, so implementation askForAnswer before produceNumber. But it isn't necessary
Pay attention to have small methods. A method shouldn't have much to do - I think that askForAnswer you could split to two methods