Home > OS >  I created the method but I can't call it in main
I created the method but I can't call it in main

Time:10-12

I want to call the method calculationsMethod from main to perform the calculations and display the results but I don't know how to proceed. Please help.

import java.util.Scanner;
public class JavaHomework1 {

static void calculationsMethod() {
   Float perimeter = ((2*length)   (2*breadth));
   Float area = ((length*breadth));
   System.out.println("The Perimeter of the Rectangle is "   perimeter);
  }

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Input the length of the rectangle: ");
    Float length = input.nextFloat();

    System.out.println("Input the breadth of the rectangle: ");
    Float breadth = input.nextFloat(); 
    input.close();
    // I want to send length and breadth to the above method for the calculation
    calculationsMethod(); // then call the method for displaying the results
    
}

}

CodePudding user response:

So basically your variables only existed in the scope of main(), the only thing missing was declaring them as fields in the method.

import java.util.Scanner;
public class Stack {

    //You did not declare them or call them to the method, 
    //so that's why your method didn't recognise length or breadth
static void calculationsMethod(Float length, Float breadth) {
   Float perimeter = ((2*length)   (2*breadth));
   Float area = ((length*breadth));
   System.out.println("The Perimeter of the Rectangle is "   perimeter);
  }

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Input the length of the rectangle: ");
    Float length = input.nextFloat();

    System.out.println("Input the breadth of the rectangle: ");
    Float breadth = input.nextFloat(); 
    input.close();
    //So basically your length and breadth only existed in the scope of main().
    calculationsMethod(length, breadth); 
    
}

}

This works:

This is it working!

  • Related