0

I'm a beginning java programmer. I'm trying to write a simple program to calculate how much of a substance remains in your body based on the half-life of the substance, and when equilibrium will be reached based on when and how the medication is taken (the latter is not yet complete).

I initially had troubles with a resource leak on my scanner, but I found the answer to that here. However, now that I've fixed the scanner, I can't seem to initialize a constant double variable as user input. The scanner itself WORKS, and the variable gains the input value, however java keeps rejecting it saying "DOSE cannot be resolved to a variable". I even put a System.out.println(DOSE); after the scanner input to test if the scanner was working, and it was. But the program will not run unless I initialize the variable further down in the program, which just overwrites the previously, successfully input value for DOSE!

I currently have the final double DOSE = 5 initialization commented, which is what throws the error. If I take those comment slashes out, then the program works fine, but the user input is irrelevant.

I tried to find the solution on here but I was unsuccessful.

package halflife;
import java.util.Scanner;
public class HalfLifeCalculation {
    public static void main(String[] args) {

        //variables scanner designated
        Scanner input = new Scanner(System.in);
        try {
            System.out.print("Enter your daily dose: ");
            double DOSE = input.nextDouble();
            System.out.println(DOSE);
        } finally {
            input.close();

        } //try end

        //variables pre-set
        int day = 2;        
        //final double DOSE = 5;
        final double HALFLIFE = 0.175;
        double result = (DOSE*HALFLIFE);

        //pre-calculated header
        System.out.println("Day 1\nRemaining substance is " + result + " mg\n");

        //while loop calculation
        while (day < 101) {
            System.out.println("Day " + day);
            System.out.println("Remaining substance is " + (result = (result + DOSE)*HALFLIFE) + " mg\n");
            day++;

        } //while end
    } //main end
} //class end
fischbs
  • 55
  • 1
  • 2
  • 8

1 Answers1

0

your are create DOSE variable inside try block means

{
     double DOSE  = input.nextDouble();
}

did you see that, DOSE wrapped in a brackets, that is called variable scope. so out side of the scope nobody know about that DOSE..

so try something like

double DOSE = 0;
try{
   DOSE = input.nextDouble();
}
subash
  • 3,116
  • 3
  • 18
  • 22