Using local declared variables in a different method in Java - java

I am having a little difficulty with a school assignment, long story short I declared two local variables in a method and I need to access those variables outside the method :
public String convertHeightToFeetInches(String input){
int height = Integer.parseInt(input);
int resultFeet = height / IN_PER_FOOT;
int resultInches = height % IN_PER_FOOT;
Math.floor(resultInches);
return input;
}
I would have to print the following string in a different method :
System.out.println("Height: " + resultFeet + " feet " + resultInches + " inches");
Any suggestions?
Thank you.

You can't access local variables outside of the scope they are defined. You need to change what is return by the method
Start by defining a container class to hold the results...
public class FeetInch {
private int feet;
private int inches;
public FeetInch(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}
public int getFeet() {
return feet;
}
public int getInches() {
return inches;
}
}
Then modify the method to create and return it...
public FeetInch convertHeightToFeetInches(String input) {
int height = Integer.parseInt(input);
int resultFeet = height / IN_PER_FOOT;
int resultInches = height % IN_PER_FOOT;
Math.floor(resultInches);
return new FeetInch(resultFeet, resultInches);
}

You can't access local variables from method A in method B. That's why they are local.
Take a look: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
As such, local variables are only visible to the methods in which they
are declared; they are not accessible from the rest of the class.
I recommend to use solution written by #MadProgrammer - create class which contains feet and inches.

You need to create a shared variable that holds your result or you encapsulate the result in a single object and then return to caller method, it may be class like result
public class Result {
public final int resultFeet;
public final int resultInches;
public Result(int resultFeet, int resultInches) {
this.resultFeet = resultFeet;
this.resultInches = resultInches;
}
}
Now, you make a result,
public Result convertHeightToFeetInches(String input){
int height = Integer.parseInt(input);
int resultFeet = height / IN_PER_FOOT;
int resultInches = height % IN_PER_FOOT;
Math.floor(resultInches);
return new Result(resultFeet, resultInches);
}
Use this result in other function to print result.
Result result = convertHeightToFeetInches(<your_input>);
System.out.println("Height: " + result.resultFeet + " feet " + result.resultInches + " inches")

Related

About having various constructors and parameters for java

I have written the instructions below and till now, I've came up with having two parameters and letting the method to assign the value and retrieving it. However, one of the instruction I had to follow was to include one constructor with no parameters, so I'm wondering what statement should I make inside the constructor without any parameters. It would be wonderful if anyone gives be a instruction. This is the code I've came up so far.
public class Rectangle {
//first constructor no parameters
//public<class name> (<parameters>)<statements>}
//two parameters one for length, one for width
//member variables store the length and the width
//member methods assign and retrieve the length and width
//returning the area and perimeter
static int recPerimeter(int l, int w) {
return 2*(l+w);
}
static int recArea(int l, int w) {
return l*w;
}
public static void main(String[] args) {
int p = recPerimeter(5, 3);
System.out.println("Perimeter of the rectangle : " + p);
int a = recArea(5,3);
System.out.println("Area of the rectangle : " + a);
}
}
First off, I would take some time to read the java tutorials. At least the "Covering the Basics"
There is a ton wrong with your example. You should store the the attributes of a rectangle - width and length as data members of the class which will get initialized with values through the constructors. If a default constructor is called with no values, then set the attributes to whatever you want. I set them to zero in the example.
Also, you need to normally create an instance of your class and then access it. Big red flag if you are having to prepend "static" to everything.
public class Rectangle {
private int recLength;
private int recWidth;
public Rectangle() {
recLength = 0;
recWidth = 0;
}
public Rectangle( int l, int w ) {
recLength = l;
recWidth = w;
}
public int calcPerimeter() {
return 2*(recLength+recWidth);
}
public int calcArea() {
return recLength*recWidth;
}
public static void main (String [] args) {
Rectangle rec = new Rectangle(5,3);
System.out.println("Perimeter = "+ rec.calcPerimeter());
System.out.println("area = " + rec.calcArea());
}
}

Passing two variables to one method to get two results

I am trying to pass two variables along to a method and have the method give me back two independent results.
int numX = 5;
int numY = 3;
System.out.println(displayTwiceTheNumber(numX, numY));
}
public static int displayTwiceTheNumber(int numX, int numY) {
int numW, numZ;
numW, numZ = 2 * (numX, numY);
return numW numZ;
}
Java takes it that at numW, numZ = 2 * (numX, numY); that I am trying to redefine numX and numY. How do I phrase the last block to take two variables and give two results?
A single int function can only return 1 int at a time.
If you want to return 2 values, consider calling the function twice or creating a custom object to be used.
You need to change the return type of the function. Currently, the return type is int, so you have to return one integer.
To return two integer, you should consider returning an array or a list or something similar.
public static int[] displayTwiceTheNumber(int numX, int numY){
//your code that do something
int[] ret = {numW, numZ};
return ret;
}
Or knowing that this function would change the value of numW and numZ, you could declare those as global variable. Now, when you call this function, those variable will be changed. Then, you can use numW and numZ subsequently.
public int numW;
public int numZ;
public static void displayTwiceTheNumber(int numX, int numY){
//your code that do something and modifies numW and numZ
}
public static void anotherfunction(){
//after calling displayTwiceTheNumber, numW and numZ would have the appropriate value
//you can now just use numW and numZ directly
}
Overview: Use a tuple. In this example I use an tuple to return more than one result. Tuple means to return more than one result type. In this example I return a tuple of two integer types. My class TupleCustom contains one method function1 which receives two parameters of type integer: x and y. I create a tuple of type integer and return the tuple as a variable. Internally, the precomiler converts the tuple json than back to a tuple with variable Item1, Item2...ItemN in the unit test method.
public class TupleCustom
{
public async Task<Tuple<int, int>> Function1(int x, int y)
{
Tuple<int, int> retTuple = new Tuple<int, int>(x, y);
await Task.Yield();
return retTuple;
}
}
public class TestSuite
{
private readonly ITestOutputHelper output;
public TestSuite(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public async Task TestTuple()
{
TupleCustom custom = new TupleCustom();
Tuple<int, int> mytuple = await custom.Function1(1,2);
output.WriteLine($" Item1={mytuple.Item1} Item2={mytuple.Item2} ");
}
When I have this problem I create a private utility class for handling the return values. By doing it this way, you can pass various types in the argument list. Aspects of the class can be tailored to your requirements.
public static void main(String [] args) {
int numX = 5;
double numY = 3.0;
Nums n = displayTwiceTheNumber(numX, numY);
System.out.println(n.numX);
System.out.println(n.numY);
}
public static Nums displayTwiceTheNumber(int numX, double numY) {
int numW;
double numZ;
// do something with arguments.
// in this case just double them and return.
return new Nums(2*numX, 2*numY);
}
private static class Nums {
int numX;
double numY;
public Nums(int nx, double ny) {
this.numX = nx;
this.numY = ny;
}
public String toString() {
return "(" + numX + ", " + numY +")";
}
}
Prints
10
6.0

Difference between the usage of void and int in this code

Currently a beginner, I wrote a simple program which uses getters and return values (current course). I'd like to ask when should I use the void solution and the int solution, if both gives me the same outcome?
I really hope the formatting isn't too terrible.
class Database {
String name;
int age;
String getName() {
return name;
}
int getAge() {
return age;
}
int yearsPlusFifty() {
int year = age + 50;
return year;
}
void plusFifty() {
int year2 = age + 50;
System.out.println(year2);
}
}
public static void main(String args[]) {
Database person1 = new Database();
person1.name = "Josh";
person1.age = 30;
int year = person1.yearsPlusFifty();
System.out.println("The age plus 50 is: " + year);
person1.plusFifty();
}
Use the int method (yearsPlusFifty) as that one has one responsibility - to calculate the value. Println in plusFifty is a side effect, which is not desirable. Keep the responsibilities of calculating and printing separate (makes it more reusable, testable, and easier to understand).
Basically, void should be used when your method does not return a value whereas int will be used when your method returns int value.
Now coming to your methods, they both are not same, they are doing two different things:
int yearsPlusFifty() - adding 50 and returning int value
void plusFifty() - better rename to printPlusFifty() - this method does both adding plus printing as well
int yearsPlusFifty() {//only adding and returning int value
int year = age + 50;
return year;
}
void printPlusFifty() {//adding + printing
int year2 = age + 50;
System.out.println(year2);
}

Accessing and modifying properties of a super class from sub class?

while trying to get a grasp of polymorphism and inheritance, I made a small program to demonstrate these topics. The program consists of a superclass 'Tree' and three subclasses 'Birch', 'Maple', and 'Oak'. Tree's constructor makes it so that all trees start off with a height of 20 and 200 leaves. In Tree I have an abstract method called grow().
Here's the code for Tree:
public abstract class Tree {
private int height;
private int numberOfLeaves;
public Tree()
{
height = 20;
numberOfLeaves = 200;
}
public Tree(int aheight, int anum)
{
height = aheight;
numberOfLeaves = anum;
}
public int getHeight()
{
return height;
}
public int getNumberOfLeaves()
{
return numberOfLeaves;
}
public void setNumberOfLeaves(int anum)
{
numberOfLeaves = anum;
}
public abstract String getType();
public void setHeight(int aheight)
{
height = aheight;
}
public abstract void grow();
}
Here's the code in Birch for grow().
public void grow()
{
int height = super.getHeight();
super.setHeight(height++);
int num = super.getNumberOfLeaves();
super.setNumberOfLeaves(num+=30);
System.out.println("The Birch is Growing...");
}
However, when I call code to make an array of trees grow, none of their heights or number of leaves change.
Here's the code I used to populate the array of trees (I did it manually):
ArrayList<Tree> treeArray = new ArrayList<Tree>();
treeArray.add( new Oak());
treeArray.add(new Birch());
treeArray.add(new Maple());
And Here's the code I used to call grow:
for (Tree tree : treeArray)
{
tree.grow();
System.out.println("The " + tree.getType() + "'s height is " + tree.getHeight() + " and it's number of leaves is "+ tree.getNumberOfLeaves() +".");
}
Clearly, the values in the superclass aren't being modified. Any help will be appreciated! Thanks!
Change your code to :
int height = super.getHeight();
super.setHeight(++height);
note that you don't need to call super.method(). as long as the method is protected (public even better) you can just simplify it to :
int height = getHeight();
setHeight(++height);
You only call super. if you implement the method again in your child class and want to specifically call the parent class, which usually can be seen in constructor calling parent constructor.
One more thing : your accessor need to be changed a bit just for pre-caution case. see code below. Usually your IDE should support auto generation of accessor.
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
This code:
int height = super.getHeight();
super.setHeight(height++);
isn't going to change anything, because the increment of height will occur after the call to super.setHeight(). So you're just setting the height to its current value.

Will there any issues in initializing non-static member variables this way?

I have initialized the variables as follows in the code below. Is it okay to initialize like this ?
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
public static int getInt() {
int ret = 10;
System.out.println("ret- " + ret);
return ret;
}
public static int processInt(int toProcess) {
int toRet = toProcess / 2;
System.out.println("toRet- " + toRet);
return toRet;
}
public static void main(String[] args) {
StaticInit sit = new StaticInit();
}
}
You can initialise with the variable declaration or in the constructor. Some will argue that one or the other is better but either works. I believe the argument for initialise in the constructor is so that all variable initialisations are in the same place, since not everything can be initialised outside of the constructor in some cases.
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
}
or
public class StaticInit {
int x;
String z;
public StaticInit() {
x = 10;
z = x / 2;
}
}
For this case in particular though, I would definitely recommend using the constructor since z relies on x. Plus the constructor is much nicer than using static methods.
Personally, instead of having the getInt(), I would just initialise it in the constructor.
Unless you're going to use the getInt() function externally, I don't see the point in having it, especially since it returns a hardcoded value.

Categories