2017-04-19 169 views
0

对于我将要包含的长代码的道歉。我想要做的是将某些经过验证的用户输入变量保存到对象中。我相信我的问题是由于变量范围,这就是为什么我有错误customerAccount may not have been initialized对象未被初始化由于范围

如果有人能指出我正确的方向,它将不胜感激。

import java.util.*; 
import java.io.*; 

public class ATM { 
    public void run() { 

     // USED FOR DEBUGGING PURPOSES. SET TO TRUE TO ENABLE DEBUGGING MODE 
     boolean debug = false, mainCheck = false, check = false; 
     Scanner input = new Scanner(System.in); 
     Scanner fInput = null; 
     int idNumber = 0; 
     String lastName, firstName, emailAddress, phoneNumber; 
     double startingBalance; 
     Client customerAccount; 

     File file = new File("accountData.txt"); 
     if(!file.exists()) { 
      System.out.println("File does not exist within directory. Creating file now."); 
      PrintWriter output = null; 
      try { 
       output = new PrintWriter(file); 
      } 
      catch(IOException e) { 
       System.out.println("Something went wrong during file creation."); 
      } 
      finally { 
       if (output != null) 
        output.close(); 
      } 
     } 

     ArrayList<Client> clientArr = new ArrayList<Client>(); 

     try { 
      fInput = new Scanner(new File("accountData.txt")); 
     } 
     catch(Exception e) { 
      System.out.println("ERROR: File Not Found."); 
      e.printStackTrace(); 
     } 
     while(fInput.hasNext()) { 
      try{ 
       int tempID = fInput.nextInt(); 
       String tempFName = fInput.next(); 
       String tempLName = fInput.next(); 
       String tempPNumber = fInput.next(); 
       String tempEmail = fInput.next(); 
       double tempBalance = fInput.nextFloat(); 
       Client tempClient = new Client(tempID, tempFName, tempLName, tempPNumber, tempEmail, tempBalance); 
       tempClient.getAccount().setID(tempID); 
       clientArr.add(tempClient); 

      if(debug == true) 
       System.out.println(tempID+" "+tempFName+" "+tempLName+" "+tempPNumber+" "+tempEmail+" $"+tempBalance); 
      } 
      catch(NoSuchElementException e) { 
       System.out.println("ERROR: Missing a required data field."); 
      } 
     } 

     if(debug == true) 
      System.out.println(clientArr.size()); 

     int menuChoice = 0; 
     while(menuChoice != 5) { 
      System.out.println("**********************************"); 
      System.out.println("Thank you for choosing Java World Bank!"); 
      System.out.println("Main Menu: "); 
      System.out.println("[1] Login as an existing user."); 
      System.out.println("[2] Display client list sorted by last name."); 
      System.out.println("[3] Display client list sorted by account number."); 
      System.out.println("[4] Create a new client."); 
      System.out.println("[5] Exit."); 
      System.out.println("===================================="); 
      do { 
       try { 
        System.out.println("Enter your choice: "); 
        menuChoice = input.nextInt(); 
        mainCheck = true; 
       } 
       // Checks if user enters an unexpected input (not a digit) 
       catch(InputMismatchException e) { 
        System.out.println("Invalid input! Please use a numeric value between 1 and 5."); 
        if(debug == true) 
         e.printStackTrace(); 
        input.nextLine(); 
       } 
      }while(!mainCheck); 

      switch(menuChoice) { 
       case 1: 
        System.out.println("Please enter your fist name: "); 
        input.nextLine(); 
        String loginFName = input.nextLine(); 
        while(loginFName.matches("[a-zA-Z]*") == false) { 
         System.out.println("Invalid input. First name needs to be all letters. Please try again."); 
         loginFName = input.nextLine(); 
        } 
        System.out.println("Please enter your last name: "); 
        String loginLName = input.nextLine(); 
        while(loginLName.matches("[a-zA-Z]*") == false) { 
         System.out.println("Invalid input. Last name needs to be all letters. Please try again."); 
         loginLName = input.nextLine(); 
        } 
        final String searchFName = loginFName; 
        final String searchLName = loginLName; 
        int loginValidation = 0; 

        Optional<Client> queryResult = clientArr.stream().filter(value -> value.getFName().equals(searchFName) 
                      &&value.getLName().equals(searchLName)).findFirst(); 
        if(queryResult.isPresent()) { 
         System.out.println("User "+loginFName+" "+loginLName+" successfully logged into. Welcome back to Java World Bank."); 
         menuChoice = 5; 
        } 
        else 
         System.out.println("Login failed. Returning to main menu."); 
        break; 
       case 2: 
        System.out.println("Clients of Java World Bank, sorted by last name: "); 
        clientArr.sort((p1, p2) -> p1.getLName().compareTo(p2.getLName())); 
        for(Client client : clientArr) 
         System.out.println(client); 
        menuChoice = 5; 
        break; 
       case 3: 
        System.out.println("Clients of Java World Bank, sorted by ID: "); 
        clientArr.sort((p1, p2) -> Integer.compare(p1.getAccount().getID(), 
                   p2.getAccount().getID())); 
        for(Client client : clientArr) 
         System.out.println(client); 
        menuChoice = 5; 
        break; 
       case 4: 
        System.out.println("You are now creating a new client account with Java World Bank!"); 
        System.out.println("Some information is required to create this account."); 
        System.out.println("What would you like your ID number to be? It must contain only integers."); 
        check = false; 
        do { 
         try { 
          System.out.println("Please enter your choice: "); 
          idNumber = input.nextInt(); 
          check = true; 
         } 
         catch(InputMismatchException e) { 
          System.out.println("ERROR: ID must contain integers only!"); 
          input.nextLine(); 
         } 
        }while(!check); 
        startingBalance = 0; 
        check = false; 
        // Continiously prompts user to enter valid input 
        do { 
         try { 
          System.out.println("What will be your starting balance?"); 
          startingBalance = input.nextDouble(); 
          check = true; 
         } 
         // Checks if user enters a value that is not a double 
         catch (InputMismatchException e) { 
          System.out.println("Invalid input! Please enter a numeric value."); 
          input.nextLine(); 
          if(debug == true) 
           e.printStackTrace(); 
         } 
        }while(!check); 
        customerAccount = new Client(idNumber, startingBalance); 
        System.out.println("Please enter client's first name: "); 
        firstName = input.nextLine(); 
        customerAccount.setFName(firstName); 
        // Verifies first name is only letters, either capital or lowercase 
        while(firstName.matches("[a-zA-Z]*") == false) { 
         System.out.println("Invalid input. First name needs to be all letters. Please try again."); 
         firstName = input.nextLine(); 
         customerAccount.setFName(firstName); 
        } 
        System.out.println("Please enter client's last name: "); 
        lastName = input.nextLine(); 
        customerAccount.setLName(lastName); 
        // Verifies last name is only letters, either capital or lowercase 
        while(lastName.matches("[a-zA-Z]*") == false) { 
         System.out.println("Invalid input. Last name needs to be all letters. Please try again."); 
         lastName = input.nextLine(); 
         customerAccount.setLName(lastName); 
        } 
        System.out.println("Please enter client's email address: "); 
        emailAddress = input.nextLine(); 
        customerAccount.setEmail(emailAddress); 
        // Verifies email address only uses lowercase/capital letters, dot, underscore, and/or dashes followed by @ symbol to specify domain 
        while(emailAddress.matches("^[A-Za-z0-9+_.-][email protected](.+)$") == false) { 
         System.out.println("Invalid input. Email not in valid format. Please try again."); 
         emailAddress = input.nextLine(); 
         customerAccount.setEmail(emailAddress); 
        } 
        System.out.println("Please enter client's phone number: "); 
        phoneNumber = input.nextLine(); 
        // Verifies phone number follows valid North American format 000-000-0000 
        while(phoneNumber.matches("[0-9]\\d{2}-[0-9]\\d{2}-\\d{4}") == false) { 
         System.out.println("Invalid input. Phone number must be in the following format: 123-456-7890. Please try again."); 
         phoneNumber = input.nextLine(); 
         customerAccount.setPNumber(phoneNumber); 
        } 


      // Verifies that the starting balance the user inputs is positive 
      while(startingBalance < 0) { 
       System.out.println("**********************************"); 
       System.out.println("ERROR: You can not start with a negative balance."); 
       System.out.println("Please enter a POSITIVE value for your starting balance: "); 
       startingBalance = input.nextDouble(); 
      } 

     }//end switch 
    } 
     // Debugging to verify user input is correctly stored 
     if(debug == true) { 
      System.out.println(customerAccount.toString()); 
      Account testing = customerAccount.getAccount(); 
      System.out.println("ID: "+testing.getID()+ " Balance: "+testing.getBalance()); 
     } 

     System.out.println("********************************"); 
     System.out.println("Your account has been fully initialized! Thank you for choosing Java World Bank!"); 
     System.out.println("********************************"); 

     // Loops through menu prompt until user enters 4 to quit 
     int choice = 0; 
     while(choice != 4) { 
      System.out.println("Client Menu"); 
      System.out.println("[1] Check Balance"); 
      System.out.println("[2] Withdraw"); 
      System.out.println("[3] Deposit"); 
      System.out.println("[4] Exit"); 
      System.out.println("================================="); 

      // Continiously prompts user to enter valid input 
      check = false; 
      do { 
       try { 
        System.out.println("So... What do you want to do?"); 
        choice = input.nextInt(); 
        check = true; 
       } 
       // Checks if user enters an unexpected input (not a digit) 
       catch(InputMismatchException e) { 
        System.out.println("Invalid input! Please use a numeric value between 1 and 4."); 
        if(debug == true) 
         e.printStackTrace(); 
        input.nextLine(); 
       } 
      }while(!check); 

      double amount = 0; 
      switch(choice) { 
       // Will display updated balance 
       case 1: 
        System.out.println("Your current balance is: $"+customerAccount.getAccount().getBalance()); 
        System.out.println("********************************"); 
        break; 
       // Allows user to withdraw money from current balance 
       case 2: 
        // Continiously prompts user to enter valid input 
        check = false; 
        do { 
         try { 
          System.out.println("How much do you wish to withdraw?"); 
          amount = input.nextDouble(); 
          customerAccount.getAccount().withdraw(amount); // Passes withdraw value to Account class 
          System.out.println("********************************"); 
          check = true; 
         } 
         // Validates that customer has enough money to withdraw the specified amount 
         catch(OutOfMoney error) { 
          System.out.println("You do not have enough funds to do this."); 
          System.out.println("********************************"); 
         } 
         // Validates that customer enters expected input 
         catch(InputMismatchException e) { 
          System.out.println("INVALID INPUT. Please enter a numeric value."); 
          // Used to clear input buffer after catching exception 
          input.nextLine(); 
          System.out.println("********************************"); 
         } 
        }while(!check); 

        // Debugging to make sure values are correctly calculated 
        if(debug == true) 
         System.out.println(customerAccount.getAccount().getBalance()); 
        break; 
       // Allows user to deposit money to current balance 
       case 3: 
        check = false; 
        do { 
         try { 
          System.out.println("How much do you wish to deposit?"); 
          amount = input.nextDouble(); 
          customerAccount.getAccount().deposit(amount); // Passes deposit value to Account class 
          System.out.println("********************************"); 
          check = true; 
         } 
         // Validates that user enters expected input 
         catch(InputMismatchException e) { 
          System.out.println("Invalid input. Please enter a numeric value."); 
          // Used to clear input buffer after catching exception 
          input.nextLine(); 
          System.out.println("********************************"); 
         } 
        }while(!check); 

        // Debugging to make sure values are correctly calculated 
        if(debug == true) 
         System.out.println(customerAccount.getAccount().getBalance()); 
        break; 
       // Exits program 
       case 4: 
        System.out.println("Thank you for choosing Java World Bank!"); 
        break; 
       // Checks if user does not enter 1, 2, 3, or 4 in main menu prompt 
       default: 
        System.out.println("You have entered an invalid input. Please try again."); 
        System.out.println("********************************"); 
        break; 
      } 
     } 
     input.close(); 
    } 
} 

回答

2

因为你的对象的初始化的状态下发生的,如果它被初始化或不那么你需要确保它的条件外初始化,例如使之无效的编译器无法弄清楚。

​​
+0

是不是很有趣,有时最明显的东西是直视你的脸。我想我只需要更多的咖啡。 谢谢,先生! –

+1

@NickM任何时候,如果解决了问题请接受答案 –

2

首先,你可能想在这里看到有关声明和初始化变量:here

你在这一行初始化customerAccount:customerAccount = new Client(idNumber, startingBalance);

然而,如果4开关内时发生。然后在这一行System.out.println(customerAccount.toString());您尝试访问customerAccount的toString函数。由于此步骤不属于第四种情况,因此可能无法初始化customerAccount。

考虑switch语句没有转到4并且debug设置为true的情况。 customerAccount将从此行申报:Client customerAccount;然而,代码路径不会以任何方式初始化它,所以你不能在它上面调用toString。

一个解决方案可能是将customerAccount初始化为null或声明为new Client(),或者只在试图初始化之后试图访问此变量。很难确定没有看到客户端类。 请注意,在空情况下,您可能必须执行一些空检查,例如,如果customerAccount为null,则customerAccount.toString()将引发异常。

+0

嗯,我需要重新构建我认为我的代码的布局。谢谢你的建议。 –

+1

没问题,我编辑了我的答案,其中包含了我错过的一些内容,最重要的是,如果它为空,那么如果您在其上调用.toString()时可能会遇到问题。你可以通过执行'Client customerAccount = null'来解决这个问题,然后当你想访问它时,执行'if(customerAccount!= null)'。 – gwcoderguy