Home > Net >  Using a final double variable in java
Using a final double variable in java

Time:10-06

I'm making a small program that asks the user for the radius of a circle and then outputs the radius, diameter, area, and circumference of the circle in java. I was asked to use a final double to declare the number pi, and I need to use that later in the code to calculate values. I'm having issues with declaring/using the variable and I'm not sure what I'm doing wrong.

I get this error when running the code:

enter image description here

Main.java :

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    final double Pi = 3.14159;
    
    Scanner keyboard = new Scanner(System.in);
    System.out.println("What is the radius of the circle? ");    
    double radius = keyboard.nextDouble();
    
    Circle circle1 = new Circle(radius);
     
    System.out.println("For a circle with diameter of " circle1.getDiameter());
    System.out.print(", a radius of " circle1.getRadius());

    // Calling the public method that prints the results
    circle1.results();
    
  }

Circle.java :

import java.lang.Math;
final double pi = 3.14159;

class Circle{
  double radius = 0.0;
  
  public Circle (){
    radius = 0.0;
  }

   Circle(double r){
    radius = r;
  }
  
  public double getRadius(){
    return radius;
  }

  public double getDiameter(){
    return radius*2;
  }  

  private double circumference(){
    return 2*pi*radius;
  }
  
  private double area(){
    return pi*(radius*radius);
  }

  public void results(){
    System.out.println("The circumcerence is: "  circumference() );
    System.out.println("The area is: "  area() );
  }
}

CodePudding user response:

It's a typo,final double pi = 3.14159; need to be declared inside Circle and final double Pi = 3.14159; is never used in Main

import java.lang.Math;

class Circle{
  double radius = 0.0;
  final double pi = 3.14159;
  
  public Circle (){
    radius = 0.0;
  }

   Circle(double r){
    radius = r;
  }
  
  public double getRadius(){
    return radius;
  }

  public double getDiameter(){
    return radius*2;
  }  

  private double circumference(){
    return 2*pi*radius;
  }
  
  private double area(){
    return pi*(radius*radius);
  }

  public void results(){
    System.out.println("The circumcerence is: "  circumference() );
    System.out.println("The area is: "  area() );
  }
}
  • Related