I am trying to create a program that has a class with a method that accepts a charge account number as an argument. Then the method should determine if the account number is valid by comparing it to the list of accounts in a text file (Accounts.txt). Then method should return a boolean value of true if the account is found. The method should use sequential search of ArrayList to find the target account.

I am instructed to use the following as the header to the method :
public static boolean isValid(ArrayList AccountList, String target)

and the logic should follow as :
Read the Accounts.txt file into an ArrayList object.
Loop through the ArrayList and display all accounts.
Prompt user for target Account to search for.
Search for account using the method.
Display Account number Valid or not Valid message.
Test for both conditions.

I have completed a large portion of the code but keep getting errors no matter what I edit. This is my first java course and I'm still trying to fully learn how to trace errors and such. Any help will be greatly appreciated. Thanks in advance.

Code thus far: (with general comment tags. Errors will be typed in comment tags within brackets. i.e. // [ error message ] )

package accountNumber;

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class AccountNumber{
public static void main(String[] args) throws IOException
{
	ArrayList<String> accountList = new ArrayList<String>();
	
	Scanner keyboard = new Scanner(System.in);
	
	System.out.print("Enter the filename: ");
	String filename = keyboard.nextLine();
	
	File file = new File(filename);
	Scanner inputFile = new Scanner(file);
	
	while (inputFile.hasNext())
	{
		String account = inputFile.nextLine();
		accountList.add(account);
	}

	inputFile.close();
	
	for (int index = 1; index < accountList.size(); index++)
	{
		System.out.println("Index: " + index + " Account: " +
							accountList.get(index));
	}
	
/** [ 	- Syntax error on token ")", ; expected
	- Syntax error on token "(", ; expected
	- Illegal modifier for parameter isValid; only final is permitted
	- Syntax error on token ",", ; expected
	- ArrayList is a raw type. References to generic type ArrayList<E> should be 
	 parameterized ] */

	public static boolean isValid(ArrayList AccountList, String target)
	{
	String test = filename;

/** [ - The method sequentialSearch(Scanner, String) is undefined for the type 
	 AccountNumber
	- Duplicate local variable target ] */

    int target = sequentialSearch(inputFile, filename);

    if (target == -1)
    {
       System.out.println("Invalid account number.");
    }
    else
    {
       System.out.println("Account number is valid." + (target + 1));
    }
 }
 
 /**
    The sequentialSearch method searches an array for
    a value.
    @param array The array to search.
    @param value The value to search for.
    @return The subscript of the value if found in the
            array, otherwise -1.
 */
  
**/ [- Syntax error on token ",", ; expected
	- Syntax error on token ")", delete this token
	- Duplicate local variable filename
	- Illegal modifier for parameter sequentialSearch; only final is 
	 permitted
	- Duplicate local variable inputFile
	- Syntax error on token "(", ; expected ] */
	public static int sequentialSearch(int[] inputFile,int filename);
 {
    int index;        // Loop control variable
    int element;      // Element the value is found at
    boolean found;    // Flag indicating search results

    // Element 0 is the starting point of the search.
    index = 0;

    // Store the default values element and found.
    element = -1;
    found = false;

    // Search the array.
    while (!found && index <inputFile.length)
    {
       if (inputFile[index] == filename)
       {
          found = true;
       }
       index++;
    }
 }
}
}
Attachments
5658845
4520125
7895122
8777541
8451277
1302850
8080152
4652555
5552012
5050552
7825877
1250255
1005231
6545231
3852085
7576651
7881200
4581002

Duplicate local variable 'target' means exactly what it says - you have the same variable declared twice in the same method, which is not allowed. In your method header you have "ArrayList AccountList, String target" but then below, you said "int target" which is attempting to re-declare the variable target. You can't do that, name one of them something different or get rid of one of them. PS, the reason for the "ArrayList is a raw type" message is because of Java generics (don't worry about it for now), just know that if you are expecting your method to take an ArrayList of Strings (which you are), then you would say "ArrayList<String> AccountList". And btw, variable names, by convention (i.e. people almost always do it this way) are named in camel case, starting with lower, so you should make it "ArrayList<String> accountList".

You also have the error message:

[ The method sequentialSearch(Scanner, String) is undefined for the type AccountNumber ]

That's because your method header is defined as "public static int sequentialSearch(int[] inputFile,int filename);" ... but if you look in your code, you called it using

sequentialSearch(inputFile, filename);

The problem is that the name of the parameter does not matter when you are calling a method, it is the type that matters. Since you declared "inputFile" as a Scanner (in your main method), then you called sequentialSearch using a Scanner, which it does not take, you got an error.

Again: the sequentialSearch method, according to your code, takes two parameters: int[] and int, but you passed it a Scanner, hence the compiler gave you an error.

Hope that helps

1) How fancy are you allowed to get with this?
2) Since you KNOW the input file name, do you need to scan for it?
3) I would suggest multiple functions to help keep the actions separate and your design clean.

[Functions I would suggest]
1) main
2) public static boolean LoadInputFile(String strFileName, ArrayList<String> lstAccounts, String strError)
3) public static void displayAllAccounts(ArrayList<String> AccountList)
4) public static String getAccNumFromUser()
5) public static boolean isValid(ArrayList AccountList, String target)

With multiple functions, your "main" will stay really clean and debugging will be easier.

Edited 7 Years Ago by thines01: typo

That would be nice, but if you read his code and his errors, he clearly is having problems with passing the correct arguments into his current methods. Creating more methods at this point will only add to the chaos. His problem right now is that he needs to grasp how methods work and how the compiler enforces the correct parameters being passed.

The instructor told us that we had to follow his guidelines (at the top of the 1st post). To clean things up and try to look at things from a somewhat different angle I have deleted back down to just printing out the list of elements from the read in file (accounts.txt) and have left the area to create the search open other than the method head he wants us to use. I emailed him and his only response was sending me an example search so I will include that code as well to show what style he is wanting us to use. As I said, I had most of the code before I posted on here and am now stuck on the search part.

My cleaned up code (working if take out the last method header)

package assignment8;

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Assignment8{
public static void main(String[] args) throws IOException
{
	ArrayList<String> accountList = new ArrayList<String>();
	
	Scanner keyboard = new Scanner(System.in);
	
	System.out.print("Enter the filename: ");
	String filename = keyboard.nextLine();
	
	File file = new File(filename);
	Scanner inputFile = new Scanner(file);
	
	while (inputFile.hasNext())
	{
		String account = inputFile.nextLine();
		accountList.add(account);
	}

	inputFile.close();
	
	for (int index = 0; index < accountList.size(); index++)
	{
		System.out.println("Index: " + index + " Account: " +
							accountList.get(index));
	}
	
	**/ take out this and the program reads out the files and only leaves the searching for specific file part to do./*
public static boolean isValid(ArrayList AccountList, String target)
	{
		
	}
}
}

The example he sent me :

/**
   This program sequentially searches an
   int array for a specified value.
*/

public class SearchArray
{
   public static void main(String[] args)
   {
      int[] tests = { 87, 75, 98, 100, 82 };
      int results;

      // Search the array for the value 100.
      results = sequentialSearch(tests, 100);

      // Determine whether 100 was found and
      // display an appropriate message.
      if (results == -1)
      {
         System.out.println("You did not " +
                    "earn 100 on any test.");
      }
      else
      {
         System.out.println("You earned 100 " +
                    "on test " + (results + 1));
      }
   }
   
   /**
      The sequentialSearch method searches an array for
      a value.
      @param array The array to search.
      @param value The value to search for.
      @return The subscript of the value if found in the
              array, otherwise -1.
   */

   public static int sequentialSearch(int[] array,
                                      int value)
   {
      int index;        // Loop control variable
      int element;      // Element the value is found at
      boolean found;    // Flag indicating search results

      // Element 0 is the starting point of the search.
      index = 0;

      // Store the default values element and found.
      element = -1;
      found = false;

      // Search the array.
      while (!found && index < array.length)
      {
         if (array[index] == value)
         {
            found = true;
            element = index;
         }
         index++;
      }

      return element;
   }
}

I have canceled my plans for Halloween X( just to give myself more time to work on this since its due noon Tue CDT.

Thanks for the assistance and I hope I can figure this out.

I know it's probably basic errors that you have described how to fix before now but I am falling asleep at the keyboard (its 5AM here and I've been up for almost 20 hrs) and wanted to post what I had done since I "cleaned up". If it's too bad to work with, I don't mind deleting it.

Here is the code with the errors in the braces just as before.

package assignment8;

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Assignment8{
public static void main(String[] args) throws IOException
{
	ArrayList<String> accountList = new ArrayList<String>();
	
	Scanner keyboard = new Scanner(System.in);
	
	System.out.print("Enter the filename: ");
	String filename = keyboard.nextLine();
	
	File file = new File(filename);
	Scanner inputFile = new Scanner(file);
	
	while (inputFile.hasNext())
	{
		String account = inputFile.nextLine();
		accountList.add(account);
	}

	inputFile.close();
	
	for (int index = 0; index < accountList.size(); index++)
	{
		System.out.println("Index: " + index + " Account: " +
							accountList.get(index));
	}
}

	
	/** [ Multiple markers at this line
	- This method must return a result of type boolean
	- ArrayList is a raw type. References to generic type ArrayList<E> should be 
	 parameterized ]  I understand why I got the return error, but I'm not sure how to go about keeping the header the way the instructor wants while following the example and making the program work. I remember bout the raw type part as well. */

public static boolean isValid(ArrayList AccountList, String target)
	{
		Scanner keyboard = new Scanner(System.in);
		
		System.out.println("Enter your account number : ");
		String accountNumber = keyboard.nextLine();
		
		int valid;
		
		valid = sequentialSearch(target, accountNumber);
		
		if (valid == -1)
		{
			System.out.println("You did not enter a valid account number");
		}
		else
		{
			System.out.println("Your account number has been verified");
		}
	}

	
	public static int sequentialSearch(String array, String file)
	{
		int index;
		int element;
		boolean valid;
		
		index = 0;
		
		element = -1;
		valid = false;
		
		while (!valid && index < array.length())
			{

/** [The type of the expression must be an array type but it resolved to String ]  referring to the array[index] of the following if statement */

				if (array[index] == file)
				{
					valid = true;
					element = index;
				}
				index++;
			return element;			   
		}
	}
}

Thanks again

comment code backwards on the "clean up" post. Sorry. Drowsiness showing. lol

I know that I'm putting in a lot before everyone get a chance to look at what I have posted, but here is what I've tried.

This is only the function used to search for the array at the bottom. I only get one error but even if it's solved, I don't know if this will work. Look back at the last few post before this one if it does not look worth working with. lol

public static boolean valid(ArrayList AccountList, String target)
	{
    // check to see if the number is valid
        if (isValid(AccountList, target) == true )
            {
            System.out.println("That number is valid.");
            }
        else {
            System.out.println("That number is invalid.");
        }
            return true;
        }		   
	
	public static boolean isValid(ArrayList AccountList, String target)
		{
			int index;
			int element;
			boolean valid;
			
			index = 0;
			
			element = -1;
			valid = false;
			
			Scanner keyboard = new Scanner(System.in);
			System.out.print("Please enter an account number: ");
	        // get the number from the user
	        int accountNumber = keyboard.nextInt();
	        
			while (!valid && index < AccountList.size())
				{
/** Error says that "filename" is undefined, but it is in the main function. I don't know. */
					if (filename(accountNumber) == true)
					{
						valid = true;
						element = index;
					}
					index++;
					
				return valid;
				}
			}
		}

You're using filename as if it was a method, but it is not a method. It is a variable of type String. And also, since filename was declared in the main method, you cannot use it in any other method. If you want to use a variable from one method in another method, you must pass it as a parameter. Examples of parameters for your isValid function are your AccountList and target.

I don't want to use it as a method. I'm was using the example he provided and tried to copy how it was laid out. How would I get the variable passed to that method while still keeping the method header that the instructor told us to use?

(from first post)
"I am instructed to use the following as the header to the method :
public static boolean isValid(ArrayList AccountList, String target)"

I don't understand what he wants us to use "target" for either. That may be my problem.

I posted the clean up post so to take it back to the basic working printing out the elements in the file for the array. Even with the example he sent me that I posted, I am still having problems understanding how to do it. I'm not asking for you to do it for me, but I guess the phrase "dumb it down" from what he is wanting us to do to my level applies. lol. I'm still working on it but I don't see how I can pass as a parameter without adding it to the header he told us to use.

I appreciate your help. I'm going to work on it some more before I head to bed.

Edited 7 Years Ago by Ryujin89: n/a

Ignoring the last few post, how would i modify the example to make it search the input file instead of a defined list such as it does in the example? In short, I want to figure out how to modify the example. I have and am working on it now but I can't figure it out. The assignment is due roughly 13 hrs from the time this is posted (noon central time US). I would greatly appreciate any assistance possible.

If you ask a more specific question, or tell me exactly what isn't working, I'll help you out. After 12 straight hours of coding an iphone project that uses the google maps API, kinda tired though.

edit: when I say specific, that isn't what I meant, you were plenty specific, sorry. Its just that there are a lot of examples in this thread, so if you want help with a particular thing, you should repost the specific method/code you are talking about, say what you want to accomplish (i.e. what the code is supposed to do) and tell us any other info that would be helpful. Otherwise, if you're just stuck in general (i.e. you don't understand some concept) please restate it a little differently and I'll help you.

Edited 7 Years Ago by BestJewSinceJC: n/a

This is the post I was referring to. Sorry. I'm just frustrated at myself for not being able to figure this out. Thank you for putting up with all this and assisting me.

The instructor told us that we had to follow his guidelines (at the top of the 1st post). To clean things up and try to look at things from a somewhat different angle I have deleted back down to just printing out the list of elements from the read in file (accounts.txt) and have left the area to create the search open other than the method head he wants us to use. I emailed him and his only response was sending me an example search so I will include that code as well to show what style he is wanting us to use. As I said, I had most of the code before I posted on here and am now stuck on the search part.

My cleaned up code (working if take out the last method header)

package assignment8;

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class Assignment8{
public static void main(String[] args) throws IOException
{
	ArrayList<String> accountList = new ArrayList<String>();
	
	Scanner keyboard = new Scanner(System.in);
	
	System.out.print("Enter the filename: ");
	String filename = keyboard.nextLine();
	
	File file = new File(filename);
	Scanner inputFile = new Scanner(file);
	
	while (inputFile.hasNext())
	{
		String account = inputFile.nextLine();
		accountList.add(account);
	}

	inputFile.close();
	
	for (int index = 0; index < accountList.size(); index++)
	{
		System.out.println("Index: " + index + " Account: " +
							accountList.get(index));
	}
	
	**/ take out this and the program reads out the files and only leaves the searching for specific file part to do./*
public static boolean isValid(ArrayList AccountList, String target)
	{
		
	}
}
}

The example he sent me :

/**
   This program sequentially searches an
   int array for a specified value.
*/

public class SearchArray
{
   public static void main(String[] args)
   {
      int[] tests = { 87, 75, 98, 100, 82 };
      int results;

      // Search the array for the value 100.
      results = sequentialSearch(tests, 100);

      // Determine whether 100 was found and
      // display an appropriate message.
      if (results == -1)
      {
         System.out.println("You did not " +
                    "earn 100 on any test.");
      }
      else
      {
         System.out.println("You earned 100 " +
                    "on test " + (results + 1));
      }
   }
   
   /**
      The sequentialSearch method searches an array for
      a value.
      @param array The array to search.
      @param value The value to search for.
      @return The subscript of the value if found in the
              array, otherwise -1.
   */

   public static int sequentialSearch(int[] array,
                                      int value)
   {
      int index;        // Loop control variable
      int element;      // Element the value is found at
      boolean found;    // Flag indicating search results

      // Element 0 is the starting point of the search.
      index = 0;

      // Store the default values element and found.
      element = -1;
      found = false;

      // Search the array.
      while (!found && index < array.length)
      {
         if (array[index] == value)
         {
            found = true;
            element = index;
         }
         index++;
      }

      return element;
   }
}

I have canceled my plans for Halloween X( just to give myself more time to work on this since its due noon Tue CDT.

Thanks for the assistance and I hope I can figure this out.

I am trying to create a program that has a class with a method that accepts a charge account number as an argument. Then the method should determine if the account number is valid by comparing it to the list of accounts in a text file (Accounts.txt). Then method should return a boolean value of true if the account is found. The method should use sequential search of ArrayList to find the target account.

I am instructed to use the following as the header to the method :
public static boolean isValid(ArrayList AccountList, String target)

and the logic should follow as :
Read the Accounts.txt file into an ArrayList object.
Loop through the ArrayList and display all accounts.
Prompt user for target Account to search for.
Search for account using the method.
Display Account number Valid or not Valid message.
Test for both conditions.

I know you wanted me to simplify and "put straight forward" what I wanted, which I did. However, I was working on it since I made that last post and I believe I might have it now (close but not working yet).

The program will run and print out the account numbers in the input-ed (word? lol) file. Then ask for the account name and then stops there. I believe it has a lot to do with the "if" statement in the lower most function that actually does the search.

Any variable re-naming or other clean-up is appreciated. Too tired to think of better names.


Here is my code.

package assignment8;

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

public class Assignment8{
public static void main(String[] args) throws IOException
{
	ArrayList<String> AccountList = new ArrayList<String>();
	
	Scanner keyboard = new Scanner(System.in);
	
	System.out.print("Enter the filename: ");
	String filename = keyboard.nextLine();
	
	File file = new File(filename);
	Scanner inputFile = new Scanner(file);
	
	while (inputFile.hasNext())
	{
		String account = inputFile.nextLine();
		AccountList.add(account);
	}

	inputFile.close();
	
	for (int index = 0; index < AccountList.size(); index++)
	{
		System.out.println("Index: " + index + " Account: " +
							AccountList.get(index));
	}
	
	String target = "Your account number has been verified.";
	
	isvalid(AccountList, target);
	

}
		
	
	public static boolean isvalid(ArrayList AccountList, String target)
	{
		Scanner keyboard = new Scanner(System.in);
		
		System.out.print("Please enter an account number: ");
        // get the number from the user
        int AccountNumber = keyboard.nextInt();
        
		int results;

		      results = binarySearch(AccountList, AccountNumber);
		      
		      if (results == -1)
		      {
		         System.out.println("That is not " +
		                    "a valid account number.");
		      }
		      else
		      {		    	  
		         System.out.println (target);
		      }
		      
		      return true;
		   }
		  
		   public static int binarySearch(ArrayList accountList, int AccountNumber)
		   {
		      int index;      
		      int correct = -1;
		      boolean found;    
		     
		      index = 0;
		      
		      found = false;

		      Collections.sort(accountList);
 
		      while (!found && index < accountList.size())
		      {

/** This is where I believe the error is and why it's not working. */

		    	  if (correct != 1) 
		    	  {
		    		  int search = Collections.binarySearch(accountList,AccountNumber);   		   
		    		  found = true;
		    		  correct = 1;
		    	  }
		         index++;

/** Compiler gave error messages stating that it didn't return int if I didn't repeat it. idk.*/

		      return correct;  
		      }
			return correct;
		   }
		   }

Edited 7 Years Ago by Ryujin89: comment tags wrong.

I know that it is passed the due time, but can anyone please help me to complete this assignment for at lease partial credit? I would greatly appreciate it. I had a lot of it finished before posting and then assisted greatly by a programmer and now I need to finish it up.

Thanks and I greatly appreciate it.

I'm sure I can help you fix your binarySearch method (it looks like everything else in your program is correct). However, your instructions specifically state: "The method should use sequential search of ArrayList to find the target account." Your program doesn't use a sequential search, it uses a binary search. A sequential search would go through the ArrayList one element at a time, checking to see if each element is the one you're looking for. A binary search starts at the middle, checks to see if the element you're looking for is greater than or less than the middle. If it is greater than the middle, you now know that the element you're looking for is to the right of the middle, so now you have to look through everything to the right of the middle (using the same procedure). Your binarySearch method uses a while loop, and inside that while loop, it continuously calls Collections.binarySearch. Doing this doesn't make sense because Collections.binarySearch only needs to be called once . . and it returns either the index where your element was found ( >= 0 obviously) or it returns an integer less than 0 if your element wasn't in the array.

Now, you weren't completely off - the fact that you were using a while loop and going through your array means that you were probably trying to do a sequential search (if you look at each index, 0 through the end of the array, in order, that's sequential). But all you need to do to see if the element is in your array is this:

int index = yourList.indexOf(yourElement);

if index >= 0, the element was found in the array. If index == -1, then the element was not found in the array.

hope that helps.

This question has already been answered. Start a new discussion instead.