Generate Random Radius and Height for Cone Class in Java - java

Write a class Cone to represent a geometric cone.
Also write a main application that tests your cone class.
Provide the following methods:
A Constructor
Function Volume( )
Function SurfaceArea( )
Provide Get and Set methods for your entire
data vector.
Test all of your methods.
Loop from 1-100 and set the height and radius of
the cone using the loop counter or use random numbers.
Output the volume and surface area within the loop.
Code this far.
import java.util.Random;
class Cone{
public static void main(String []) {
Cone c = new Cone( );
Random r = new Random();
int x, y;
for (int i = 0; i < 1; i++) {
c.setR("%d");
c.setH("%d")
}
}
}

Your Random is unimplemented
c.setR(r.nextInt(99)+1);
This will randomly generate a random value between 1 and 100 and set it as your radius. You can do something similar for the height, and then finding the volume should be fairly self explanatory.

There is a significant difference between asking for help, and asking for your work to be done for you. I'd advise you to drop out of your Computer Science class if you're not willing to learn the fundamentals of Java by yourself.
Here, do something productive: https://docs.oracle.com/javase/tutorial/

Related

Issue with using array in a class Java

I am trying to build a Java program based on this UML:
UML of Polygon Class
But I ran into a few hiccups along the way. This is my basic code:
import java.util.Scanner;
public class Polygon {
private int[] side;
private double perimeter;
public double addSide(double length[]) {
int i = 0;
double perimeter = 0;
while(length[i] > 0){
perimeter += (double)length[i];
i++;
}
return perimeter;
}
public int[] getSides() {return side;}
public double getPerimeter() {return perimeter;}
public static void main(String[] args) {
Polygon polygon=new Polygon();
polygon.side = new int[99];
int i=0;
do{
System.out.print("Side length(0 when done): ");
Scanner in = new Scanner(System.in);
polygon.side[i] = in.nextInt();
i++;
}while(polygon.side[i]>0);
//polygon.perimeter = addSide((double)polygon.side);
System.out.println("Perimeter of " + i + "-sided polygon: " + polygon.getPerimeter());
}
}
There's a couple of issues.
I got it to compile but when it accepts the first side[0], it immediately stops and gives me the perimeter. Exiting the loop eventhough the conditions haven't been met for it to so. So there's an issue with my while-loop. I want it to keep accepting values into the side[] array until a non-positive value is entered.
Also the UML requires I use double parameter-type for the addSide method. I tried to cast it in the argument and tried a couple of other different things with no success. How would one transition an int-array into a double-array for the perimeter calucalation which has to be double as per the requirements.
I wouldn't surprised if I made other issues since I'm new to Java so feel free to point them out to me or if you have a better way to go about this, I would love to learn your thinking.
Any advice is appreciated!
There are a number of issues with your code.
First, differences from the UML specification:
You haven't used the given signature for addSide. The UML says that it takes a single double parameter, and returns nothing, i.e. void in Java. You are passing an array of double and returning a double.
You are directly accessing sides in your main method. Java allows you to do this, because your main method is part of the Polygon class, but the UML shows that the field is private. What does direct manipulation of sides do to the validity of the value in perimeter?
The UML shows the class having a field sides of type int. Your field sides is of type int[].
Similarly you haven't used the given signature for getSides, which should probably have been named getNumberOfSides.
Your code has quite a few other issues, but I think you should fix the issues above first.
A futher hint: The only things that the Polygon class can do is to tell you how many sides it has and what its total perimeter is. It does not care about the details of individual sides.
(Off topic, it is strange to include main in the UML description of Polygon)

Multiplying user input variables together in another class and then naming that result as a variable

Sorry if this is a bit vague. I am new to learning Java.
In my program I have two classes and one of the classes is for user input. The other class calculates that user input and then returns the calculations to the other class. In my calculations class I'm pretty sure I'm making myself work harder and than I should be. I want to have the result of my user input multiplied together but doing that in the calculations class.
Here is my Calculations class.
class Calculations{
double length, width ;
public double floorArea (double length, double width){
return length * width ;
}
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
public double serviceCharge (double length, double width){
return length * width / 10 + 12.50 ;
}
}
What I want to be able to do is have return length * width = area. Then use that area variable for future reference in the floorAreaCost method and the service charge method. So instead of return length * width * 6.50 I would have area * 6.50
Here's my user input class as well.
import java.util.Scanner;
public class ApartmentUser{
static Scanner input = new Scanner(System.in);
public static void main (String args[]){
int length, width;
System.out.println("Enter the length of the apartment floor: " );
length = input.nextInt();
System.out.println("Enter the width of the apartment floor: " );
width = input.nextInt();
Calculations area = new Calculations();
System.out.println("The area of the apartment floor is: " + area.floorArea(length, width));
Calculations cost = new Calculations();
System.out.println("The cost of the apartment is: " + cost.floorAreaCost(length, width));
Calculations charge = new Calculations();
System.out.println("The service charge cost is: " + charge.serviceCharge (length, width));
}
}
Your methods should call the floorArea method, so for example method shown below
public double floorAreaCost (double length, double width) {
return length * width * 6.50 ;
}
would become
public double floorAreaCost (double length, double width) {
return this.floorArea(length, width) * 6.50 ;
}
That way, the floor area calculation is encapsulated inside one method only and can easily change in one step
First of all you shouldn't make so many Calculations objects, one is enough.
So what you should do is give the Calculations class a constructor like this.
class Calculations{
public double length, width, area;
public Calculations (int length, int width) {
this.length = length;
this.width = width;
area = width * length;
}
Now when you create youre Calculations object:
Calculations floor = new Calculations(int length, int width);
You directly have the area calculated and you can call the methods without having to input the parameters, because they're already saved in the Calculations class.
You can also work with multiple "rooms", because the informations are saved in the Calculations class.
Hope i could help you.
As written, your Calculations class defines a "stateless" object.
Within each function, the function parameters length and width
hide the member variables length and width,
so that the member variables are never use at all.
You should be able to delete the declaration of those member variables
without noticing any change in the behavior of your program.
This is not necessarily a bad thing. Stateless classes can be very useful.
For example, because Calculations is stateless, you do not need to
allocate three different instances to perform your three different functions.
You can call all the functions on the same instance, because none of the
functions can affect the "state" of the object and therefore cannot have
any hidden "side effects" on the results of functions called later.
The return from each function is determined just by the values you
pass to its two parameters.
The program does end up multiplying the same length and width together
three times when once would have been enough.
You will hardly notice the extra computing time in this example
(it is vastly overshadowed by everything else going on here),
but if you had to do millions of these calculations for one user input
you might then notice a difference.
One way to avoid the redundant multiplications
is to return area from the floorArea function,
but pass area (not length and width) as a single parameter to
each of the other functions.
You might also consider creating member variables of Calculations
to store the numbers 6.5, 10, and 12.5 that you use in some of your functions.
That would allow you to give those numbers meaningful, descriptive names.
It would also permit a more sophisticated version of the program to accept
new values of those constants to use in a Calculations object,
allowing the store to change its pricing without rewriting its software.
If you set those values during the construction of a Calculations object
and do not change them in any of the other functions, the object
is still stateless.
Or you could decide to change the class some other way. I see at least three other answers already, each of which proposes a legitimate design of a Calculations class, no two of those designs the same.
First off all when you define fields in your class, it's common practice to define the scope of the variable. So it would look something like this. Which only makes the variable accessible within the class, if you would access it from the main method, you should declare em public. But add your area as a variable.
private double area ;
You need to store your calculated Area on the object, use the keyword this for accessing that variable. When operations on the same object is done, it can be fetched in a similar fashion.
Update your code to this:
public double floorArea (double length, double width){
this.area = length * width;
return this.area;
}
public double serviceCharge (){
return this.area / 10 + 12.50 ;
}

Method returns 0

I've made a program that generates a random number but every time it gives back 0.0
Program:
import java.util.*;
public class RandomNumber {
public static void main(String args[]){
double QuantityColors = 5;
double Mastermind = 0;
Random(QuantityColors, Mastermind);
System.out.println(Mastermind);
}
public static double Random(double QuantityColors, double Mastermind){
Mastermind = Math.random();
Mastermind = Mastermind * QuantityColors;
Mastermind = (int) Mastermind;
return Mastermind ;
}
}
I've been searching where the problem is, but the problem is in the return.
a) you are doing nothing with the result of "Random".
b) you can not modify Java argument. See change a functions argument's values?
First of all, you can use a builtin function to generate a next integer with a certain upper bound: Random.nextInt(int). For instance:
Random rand = new Random();
int masterMind = rand.nextInt(QuantityColors);
Instead of writing a Random method yourself.
It is nearly always better to use builtins since these have been tested extensively, are implemented to be rather fast, etc.
Next you seem to assume that Java uses pass-by-reference. If you perform the following call:
Random(QuantityColors, Mastermind);
Java will make a copy of the value of MasterMind. Setting the parameter in a method has no use. The only way to set a value - not encapsulated in an object - is by returning value. So:
MasterMind = Random(QuantityColors, Mastermind);
To make a long story short: the method does not return 0, you simply don't do anything useful with it.
A better solution would thus be to drop the Random method and use:
import java.util.*;
public class RandomNumber {
public static void main(String args[]){
int quantityColors = 5;
Random rand = new Random();
int mastermind = rand.nextInt(QuantityColors);
System.out.println(mastermind);
}
}
Further remarks
In your random method:
public static double Random(double QuantityColors, double Mastermind){
the MasterMind parameter is rather useless since you immediately set it with another value, so you better remove it and use a local variable instead.
Furthermore Java standards say that the name of classes, interfaces, etc. start with an uppercase; the names of methods and variables with lowercase.
Finally it is unclear why you use doubles since all the values you calculate are clearly integral.
It looks like your code would work if you wrote
Mastermind = Random(QuantityColors, Mastermind);
...because Java is pass by value, so calling a function will not change the variable you passed in.

Generate multiple draws (calls) of a given method in java (simulated lottery)

I received the task of simulating a lottery draw in java. The program skeleton yields the method generateOneDraw, which creates 6 random numbers between 1 and 49
static int[] generateOneDraw() {
int numbers[] = new int[NUMBER_OF_ELEMENT_PER_DRAW];
for(int i=0; i<numbers.length; ++i) {
int nextNumber;
do {
nextNumber = generateNextRandomNumber();
} while(numberIsInArray(nextNumber, numbers));
numbers[i] = nextNumber;
}
return numbers;
}
We are then required to implement a function that simulates the lottery draw over 5 weeks and stores them in the variable draws. I believe this should be done over a two-dimensional array. Am I right in this way of thinking? Any pointers on implementing it would be greatly appreciated.
static void generateAllDraws()
Thanks in advance.
EDIT: Nevermind, I did it with a simple two dimensional array and it worked.
Since this seems like home work, I will not go into much detail but you can either:
Create a 2 dimensional list, as per your initial reasoning;
Create a Draw class which represents a lotto draw, and create multiple instances of this class. Each Draw class could have a Date which would denote when did the draw take place.
Both approaches should work, the second approach is a little more object oriented.

How do I make two classes to work together in Java? [closed]

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 9 years ago.
I have been trying for weeks in this project where I have to make one class that generates 500 random numbers from 1-250 and in a second class I have to inherit the first class properties and write all those numbers in a text file but when I have being having problems getting the properties and work with it and I haven't found a way to do it online.
My First class is
import java.util.Random;
public class GenKeys {
public static void random(){
for (int i = 0; i < 250; i++) {
int x = (int) (Math.random() * 100);
}
}
}
and my second code is
import java.util.Random;
import java.io.*;
import java.lang.*;
public class MainProg extends GenKeys{
public static void main(String[] args){
public static void random(){
try {
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( x + System.getProperty("line.separator"));// when i compile the x is not found!!!
out.close();
} catch (IOException e) {
System.out.print(e);
}
}
How can I make the two classes work together?
What am i doing Wrong ?
You are using inheritance instead of just using an instance of GenKeys in MainProg
You keep overwriting your random values, since you only use a single variable x, when you should be using e.g. an array
You create 250 values in range [0..99] instead of 500 values in range [1..250]
You don't store or return anything from your random() method
and i havent found a way to do it online.
I'm not sure you've looked hard enough.
How to get your code working
Firstly, you want to change the type and name of your method to an int.
public static int randomNum()
Then, remove the loop from the code, and just return the random number generated:
return (int)Math.Random() * 100; //By the way there is a Random class.
In the random method, you want the loop:
for(int x = 0; x < 250; x++)
{
BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
out.write( randomNum() + System.getProperty("line.separator"));
}
out.close();
The various issues with your code
You're mis-using inheritance here. Your class is not a type of GenKey. It simply uses it, so it should be a field in your class.
Secondly, a method can only return one value, or one object. It can not return 250 numbers as is. You're assigning 250 numbers to x. This is only going to store the last number generated.
I don't think this is right approach. you need another class, for example KeyWriter to inherit from GenKeys. let it use GenKeys method random (it doesn't need to be static)
also, your random method is wrong, you only generate 250 keys instead of 500, and they are not from 0 to 250.
my solution is:
1) inherit KeyWriter from GenKeys
2) modify random to return only 1 generated number using nextInt
3) use cycle inside KeyWriter to call random 500 times and write those values into a file
4) use KeyWriter class inside you main method
I don't post the actual solution, cause it looks like you're doing your homework.
Well, somethings aren't correct here, but the weirdest of all is that you made the random() function a void.
void random()
Where X goes to? You just create a new int, but do nothing about it.
Besides this, there are other problems, as other folks mentioned around.
I'd recommend you to read about function in Java, especially about the difference between int and void.
Some problems (and comments) I see of the bat:
x is not an instance field and is not stored anywhere thus how can it be accessible from the child class.
Like others have said x is being overwritten with each iteration of your for loop.
Why is the mainProg.random() method declared inside of the mainProg.main() method?
I dont think inheritance is the way to go unless it is absolutely required for this project. Why not just make an instance of your random class inside the main method of the mainProg class?
If you want to use inheritance I believe a call to super.random() will be necessary inside of the mainProg.random() method.(Please someone confirm this. Im not 100% sure)
If it was me I would do something along the lines of this in my GenKeys.random() method:
public int[] random() {
int[] keys = new int[500];
for(int i = 0; i < 500; ++i)
{
keys[i] = (int) (Math.random() * 100);
}
return keys;
}
This code creates and returns an array of 500 keys. NOT in the range of 1-250. See here for that: How do I generate random integers within a specific range in Java?
Hopefully that will get you started on the right track.
x is the local variable of random().
so you can't directly access local variable out side the class.
And you are trying to generate 500 random no. between 1-250 so change the for loop in first class
for (int i = 0; i < 500; i++){
.....
}

Categories