![]() |
Need turning user input into an object
I need to ask a user for the radius of a circle. Which will then be turned into an object that i can use in a different class to find different measurements. My question is how do i set the user input to an object. Also how do I refernce back to the class to print out those values. Thanks.
Code:
public class Circle {Code:
import java.util.Scanner; |
You don't. You create an instance and populate it with primitive data provided by the user (and I doubt you'd ask the user to manually enter serialized data like you can from a file).
So simply ask for the nextDouble off of the scanner, and instantiate the Circle with that provided double: Circle c = new Circle(scan.nextDouble());. That will give you your circle so you can operate on the instance in the following output statements. It doesn't have any error handling in it, but I assume this is for an assignment (in which case error handling has not likely been covered)? |
Yeah we haven't covered that, but thanks that worked. Sorry I'm kinda confused on this one but is that taking the user input and setting it equal to c? I was hopping to set it equal to radius from the other class. Any idea how I do that. Thanks.
|
Nope, what that does is accepts a double from the input, and creates a new instance of Circle providing it with that double.
The only way to modify it (such as taking the radius from another class), is to construct a new instance of circle since there is currently no way to mutate the value of the radius. So if you wanted to create a new circle twice the size of an existing circle, you can use the get method on it: Circle doubleSizeCircle = new Circle(smallerCircleInstance.getRadius());. Now, the current class definition you have for Circle has a package level access to the variables, but I always assume that the variables will be private unless its final.Edit: To expand a bit, since the scope of your current circle's radius property is package accessible, you can actually modify it directly: PHP Code:
PHP Code:
|
Okay than you for your help so far. I'm not sure if I understand are you saying I can't change the value of radius in the other class?
Here's the constructors I'm trying to call Code:
public class Circle {Code:
import java.util.Scanner; |
| All times are GMT +1. The time now is 05:45 PM. |
Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.