Results 1 to 2 of 2

Thread: Variable declared in If statement issue

Hybrid View

  1. #1
    Join Date
    Dec 2011

    Variable declared in If statement issue

    I just started doing tests in order to prepare for a project I have in mind and I've already run into a problem. The basics of what I want to do is to run the program and have the user enter a name or a number that corresponds to a certain item (Each item has 1 name and 1 number. It is normal for the number to be written in multiple ways. ex: 1, 01, 001).

    When the user enters a name or number, it will read a certain text file, use a regular expression to extract some data and display it. For example, the user types 001, or "bulbasaur", then the program will read the file that goes with bulbasaur, and print the data specified by the regular expression.

    Which file is read is determined by user input, which leads me to believe that the file should be declared within an if statement. Example:

    if( cleanName.equals("bulbasaur") || cleanName.equals("1")) {
    fileName = "src\\\\bulbasaur.txt";
    The code then goes on to read the specified file. However, as I discovered, if a variable is declared within an if statement (Or any type of statement using {}), then it cannot be read outside of that block. After doing some research, I discovered I could get around this by using the if else ternary operator.

    So here is where my question finally comes in. There will be a total of 151 items (And thus 151 text files) that can possibly be read, depending on user input. So this is what I did to test reading between two text files:

    filename = (cleanName.equals("bulbasaur") || cleanName.equals("1")
    				|| cleanName.equals("01") || cleanName.equals("001")) 
    				? "src\\\\bulbasaur.txt"  : (cleanName.equals("charmander") 
    				|| cleanName.equals("2") || cleanName.equals("02") 
    				|| cleanName.equals("002")) ? "src\\\\charmander.txt" 
    				: "null";
    I know it doesn't look really neat, but it does work the way I want it to. And it extracts the appropriate data from either text file. However, still doing research, I've seen many people saying this is 'abuse', and all in all this is not a good thing to do within my code.

    So, understanding what it is I am trying to accomplish, I was wondering if anyone knew a more "best practices"/ "acceptable" method to doing what it is I hope to do? Any ideas would be greatly appreciated. I hope I provided enough information.

  2. #2
    Join Date
    Dec 2011
    Issue resolved.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center