compiler errors - In Java, how can I use a variable initialized inside a try/catch block elsewhere in the program? -
i have basic quadratic formula program, i've modified beginning end program if value other double entered. however, because i've done this, can't seem able use value inputted anywhere else in program. here first few lines:
import java.util.scanner; public class quadraticformula { public static void main(string[] args) { double a, b, c; scanner reads = new scanner(system.in); system.out.println("general equation: \"ax^2 + bx + c\""); system.out.print("enter value of \"a\": "); try { string doublestring = reads.nextline(); = double.parsedouble(doublestring); } catch (exception e) { system.out.println("invalid data type. please enter number"); }
the rest of program asks values of b , c, , carries out quadratic equation, retuning roots of whatever equation entered. however, because value of defined inside try section, compiler tells me hasn't been initialized. how fix this?
edit: want use data inputted user in program (stored doublestring)––but number. immediate problem compiler error, there way use information inputted though it's inside try block? because when tried equate double double doublestring outside block said doublestring didn't exist.
like @elliot frisch said, can initialize a value (0) , take care don't wrong values due failed parsing. in case mean return/exit program error message.
this common pattern.
import java.util.scanner; public class quadraticformula { public static void main(string[] args) { double = 0, b, c; scanner reads = new scanner(system.in); system.out.println("general equation: \"ax^2 + bx + c\""); system.out.print("enter value of \"a\": "); try { string doublestring = reads.nextline(); = double.parsedouble(doublestring); } catch (exception e) { system.out.println("invalid data type. please enter number"); return; } //do work
Comments
Post a Comment