In Java, how can I use a variable initialized inside a try/catch block elsewhere in the program?

时间:2016-04-21 22:46:33

标签: java compiler-errors try-catch variable-initialization

I have a basic quadratic formula program, but I've modified the beginning to end the program if any value other than a double is entered. However, because I've done this, I can't seem to be able to use the value inputted anywhere else in the program. Here are the 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();
      a = Double.parseDouble(doubleString); 
    }
    catch (Exception e) {
      System.out.println("Invalid Data Type. Please enter a number");
    }

The rest of the program asks for the values of b and c, and then carries out the quadratic equation, retuning the roots of whatever equation was entered. However, because the value of a is defined inside the try section, the compiler tells me that a hasn't been initialized. How do I fix this?

EDIT: I do want to use the data inputted by the user in the program (stored as doubleString)––but a number. My immediate problem is the compiler error, but is there any way to use the information inputted even though it's inside the try block? Because when I tried to equate double a to double doubleString outside the block it said doubleString didn't exist.

4 个答案:

答案 0 :(得分:0)

就像@Elliot Frisch所说,你可以将a初始化为一个值(0)并注意由于解析失败而得不到任何错误的值。 在您的情况下,这可能意味着返回/退出程序并显示错误消息。

这实际上是一种常见的模式。

import java.util.Scanner;

public class QuadraticFormula
{
public static void main(String[] args)
{
double a = 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();
  a = Double.parseDouble(doubleString); 
}
catch (Exception e) {
  System.out.println("Invalid Data Type. Please enter a number");
  return;
}
//do work with a

答案 1 :(得分:0)

只需在声明时初始化:

public static void main(String[] args)
{
  double a = 0.0;
  double b, c; 
  Scanner reads = new Scanner(System.in); 

您可以做的另一件事是将a声明为“类属性”:

public class QuadraticFormula
{
    protected static double a = 0.0; 

    public static void main(String[] args)
    {
        double b, c; 
        Scanner reads = new Scanner(System.in); 
        try { 
            String doubleString = reads.nextLine();
            QuadraticFormula.a = Double.parseDouble(doubleString); 
        }
        catch (Exception e) {
            System.out.println("Invalid Data Type. Please enter a number");
        }

请注意如何使用main()中的静态引用访问Class属性(a),因为main()是静态的,这违反了使用getter / setter访问Class属性的Java规则。我建议你做的一件事应该是开始学习如何在main()之外打包类功能......在静态引用之外......

import java.util.Scanner;

public class QuadraticFormula {

    protected  double a = 0.0;

    public static void main ( String[] args ) {
        QuadraticFormula lnewItem = new QuadraticFormula();
        try {
            lnewItem.doSomething();
        } catch ( Exception e ) {
            e.printStackTrace();
        }


    }

    public  void    doSomething () throws Exception {
        double 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();
          setA ( Double.parseDouble(doubleString) ); 
          System.out.println("setA() - [" + getA() + "]");
        }
        catch (Exception e) {
          System.out.println("Invalid Data Type. Please enter a number");
        }

    }

    public double getA () {
        return a;
    }

    public void setA ( double a ) {
        this.a = a;
    }
}

请注意,在代码的最后一部分中,除main()之外的所有静态引用都被删除。新的getter / setter方法适用于Class属性a,从而强制执行Java的数据封装。

答案 2 :(得分:0)

对此有两个修复,一个是在抛出异常时简单地从main方法返回:

   <nav class="navbar navbar-inverse">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle Navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
          </div>

        <?php 
    wp_nav_menu(
        array (
            'theme_location' => 'primary',
            'container' => 'div',
            'container_class' => '',
            'container_id'    => 'navbar',
            'menu_class' => 'nav navbar-nav'
       ) 
    ); 
?>
            </div><!--/.container-->

        </nav>
    </header>

其他人提出的另一个选择是给'a'一个初始值。我建议将其初始化为NaN(非数字),然后在使用它之前检查它是否已正确初始化:

    double a;
    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();
        a = Double.parseDouble(doubleString);
    }
    catch (Exception e) {
        System.out.println("Invalid Data Type. Please enter a number");
        return;
    }

答案 3 :(得分:-1)

而不是这一行:

double a, b, c; 

只需将其替换为:

double a=0, b, c;