Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Seaching an array confusion

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Seaching an array confusion

    Hello, so I am writing a program and had to create a one dimensional array and a two dimensional array. Here is my arrays:

     Game [] games;
    	private double[][]hoursArray = {{40, 60, 900, 400},{10,100, 800, 900},{20,70,100, 200}};
     
     
        public GameSales()
        {
        	games = new  Game[ 3 ];
    		games[ 0 ] = new Game ("Scary Halloween","Mr. Boo",1000,6091,12.99);
        	games[ 2 ] = new EGame ("Haunted House Party","Patrick Armstrong", 0, 2012,38.99,"www.SmartBook.com/IIS",180);
        	games[ 3 ] = new Game ("The Green Monster", "Game Boy", 800, 3033,6.50);
    private

    so there is my arrays and constructer. Next I have to make another method. here are the instructions. I have tries a linear search but dont know if this is a good idea. I am very confused and am looking for any help. maybe a steer in the right direction

    In this method, you will search for a specified game title. You will prompt user to enter the title of a game in string format, and search game array for the game. If the specified game is found in the game array, return the array index . Otherwise, return an integer value of 99 to indicate that the game was not on the list. You will use the result returned from this method in other method.
    **You should implement a try-catch to catch a potential exception that might occur when dealing with iterating through an array. What would that be?


    This is what i did, im not sure to use a linear search or index of

        public String FindGame()
        {
     
    		int searchString;
    		int position;
     
     
        	try
        	{
     
        		System.out.print ("Please enter game title:  ");
        		searchString = input.nextInt();
     
        		while (searchString != -1)
        		{
        			for (int index = 0; index < Game.length; index ++)
        				if ( Game[ index ] == searchString )
        					return index;
        		}
     
        	}
     
     
        	catch(InputMismatchException inputMismatchException)
        	{
        		System.err.printf ("\nExceptions:  %s\n", inputMismatchException);
        		input.nextLine();
        		System.out.println ("You must enter a String. Please try again. \n");
        	}
     
        return searchString;
        }
    private
    Last edited by ThuggedOut; October 19th, 2011 at 02:25 PM.


  2. #2
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Seaching an array confusion

    Highligt your code with:
    [highlight=Java]*Insert code here*[/highlight]

  3. #3
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Seaching an array confusion

    UHF just lost what I was gking to say.

    Here's the gist:
    I recommend:
    Use a for loop with a basic counter, continuing until you have hit the end o the games array, checking the title of the games array, returning the game if it has the title. Return null if none was found. Use a seperate method to find an index of a game. Better over the long run, because this way you don't have to access the array every time you searh for a title.

    Otherwise, same for loop but return the integer index.

  4. #4
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Seaching an array confusion

    Also, just looked at what you have. It's bad style to have a method that calls for user input
    Your code doesn't make any sense to me, so I'm assuming you want
    /*Main method or the equivalent*/
    Scanner in = new Scanner(System.in);
    System.out.println("What title do you want to search for?");
    String title = in.nextLine();
    Game g = searchByTitle(title);
    if(g == null)
      System.out.println("Game not found");
    else
    {
      System.out.println("Found: ");
      System.out.println(g.toString());
    }
    Concise, maintanible.

    Edit: For some reason I had assumed that was youre main method, probaly after I saw user input. I removed most of it but left the next paragraph because I'm curious what other people have to say about it.

    As for your searchByTitle, look for my previous code. The main method should, (in my opinion), be almost entirely interaction with the user. That way, when someone else looks at your code (EG, Teacher, Friend), they immediately know what the code does, and how it works. Of course, if your using a GUI, that's a different story, but the gist is the same.

    Edit, just looked at your code again, why are you making them search by an int?
    Last edited by Tjstretch; October 19th, 2011 at 03:07 PM.

  5. #5
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seaching an array confusion

    well this is basically my process class. I will have a different method with a main like a test class to ask the user what they would like to do. It is not finished but his is what I have done:


    public class TestClass
    {
     
        public static void main (String[] args)
        {
        	Scanner input = new Scanner (System.in);
     
        	char decision; //char variable decision
    		int sentinal = 1; //integar varaible to hold the sentinal loop counter
        	GameSales alvorp = new GameSales();
     
     
        	while(sentinal ==1 ) //sentinal controlled loop structure
         	{
     
     
         		System.out.println ("Welcome to Game Management Program\n");
    	     	System.out.println ("=====================================\n");
    	     	System.out.println ("P - Print the sales information of a specified game\n");
    	     	System.out.println ("U - Update the sales information of a specified game\n");
    	     	System.out.println ("O - Output the sales information to a text file\n");
    	     	System.out.print ("Which Item?  ");
         	    String decisionInput = input.next(); //inputs which user item choosen into decision input
         		decision = decisionInput.charAt(0); //decisioninput goes into char variable decision
     
     
         		if(decision == 'P') //nested if else statement with one condiditon
         		{
    				alvorp.PrintGameSales();
     
         		}
     
         			else if(decision == 'U') //nested if else statement with one condition
         			{
     
     
         			}
    	     			else if(decision == 'O') //nested if else statement with one condition
    	     			{
     
     
     
    	     			}
     
    		     			else
    		     				System.out.println ("Incorrect choice!"); //print statement if invaled entry is posted
     
         	}
         	    	System.out.println("Do you want to continue process another transaction? 1 - to continue and other number to quit : 1");
        			sentinal = input.nextInt(); //user input value goes into sentinal and determines whether to continue the loop
     
     
     
     
         	}

  6. #6
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seaching an array confusion

    I think i understand what your saying about prompting them for the game title. once they tell you the title you input it into the title string, then you run a for loop searching through the array and maybe with like a compareto once you find it it returns the game into G or something. Maybe i understand? i also need to return the index and it all has to be done in this find games method

  7. #7
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seaching an array confusion

    Also this is the output if it makes things clearer


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? K


    Incorrect choice!

    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? p

    Please enter the game title: Haunted House Party

    Haunted House Party 10 100 800 900

    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? U

    Please enter the game title: Scary Halloween

    Please enter the quarter (1, 2, 3, or 4): 2

    What is the new sales number? 70


    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? P

    Please enter the game title: Scary Halloween

    Scary Halloween 40 70 900 400

    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? U

    Please enter the game title: The Green Monster

    Please enter the quarter (1, 2, 3, or 4): 2

    What is the new sales number? 99


    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? P

    Please enter the game title: The Blue Monster

    The title is not in the database

    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? P

    Please enter the game title: The Green Monster

    The Green Monster 20 99 100 200

    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? o


    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? U

    Please enter the game title: Scary Halloween

    Please enter the quarter (1, 2, 3, or 4): 5

    Invalid quarter!

    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? U

    Please enter the game title: Scary Halloween

    Please enter the quarter (1, 2, 3, or 4): 3

    What is the new sales number? apple

    Exception: null
    You should enter an integer value.

    Do you want to continue process another transaction? Y - to continue and other letter to quit : Y


    Welcome to Game Management Program
    =====================================
    P - Print the sales information of a specified game
    U - Update the sales information of a specified game
    O - Output the sales information to a text file

    Please select a task? U

    Please enter the game title: Scary Halloween

    Please enter the quarter (1, 2, 3, or 4): 3

    What is the new sales number? 1000


    Do you want to continue process another transaction? Y - to continue and other letter to quit : N



    Process completed.

  8. #8
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Seaching an array confusion

    Ok, I don't understand, one quarter of your game is getting priced differently then the rest?
    It seems to be working, you don't have to explain it to me, I'm just curious. Also, a few recommendations.

    1: instead of
    String decisionInput = input.next();
    try
    String decisionInput = input.next().toUpperCase();

    Switch statement instead of all the else ifs.
    System.out.println ("Incorrect choice!"); //print statement if invaled entry
    might look better as
    System.err.println ("Invalid choice."); //print statement if invalid entry
    Last edited by Tjstretch; October 19th, 2011 at 03:36 PM.

  9. #9
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Seaching an array confusion

    Oh by the way, the exception MAY be an IndexOutOfBoundsException, but not sure why you would get that unless you don't check parameters

  10. #10
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seaching an array confusion

    here is what I came up with. What do you think?


    import java.util.Scanner;
    import java.util.InputMismatchException;
    import java.util.Formatter;
    import java.util.Arrays;
     
     
    public class GameSales implements TransactionManagementInterface
    {
     
    	Scanner input = new Scanner (System.in);
     
    	private Game [] games;
    	private double[][]hoursArray = {{40, 60, 900, 400},{10,100, 800, 900},{20,70,100, 200}};
     
     
        public GameSales()
        {
        	games = new  Game[ 3 ];
    		games[ 0 ] = new Game ("Scary Halloween","Mr. Boo",1000,6091,12.99);
        	games[ 1 ] = new EGame ("Haunted House Party","Patrick Armstrong", 0, 2012,38.99,"www.SmartBook.com/IIS",180);
        	games[ 2 ] = new Game ("The Green Monster", "Game Boy", 800, 3033,6.50);
     
        }
     
        public int FindGame()
        {
    		String searchString;
    		int indexVal;
     
    		System.out.print ("Please enter game title:  ");
        		searchString = input.next();
     
        	try
        	{
        		for(int i = 0;i< games.length; i++);
        		if ((games[i].getTitle()).equals(searchString))
        		{
        			indexVal = i;
        		}
        			else
        			{
        				indexVal = 99;
        			}
     
        	}
     
    	    	catch(InputMismatchException inputMismatchException)
    	    	{
    	    		System.err.printf ("\nExceptions:  %s\n", inputMismatchException);
    	    		input.nextLine();
    	    		System.out.println ("You must enter a String. Please try again. \n");
    	    	}
     
        return indexVal;
        }

  11. #11
    Junior Member
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Seaching an array confusion

    So do you think I should put another catch statement?

  12. #12
    Forum VIP
    Join Date
    Oct 2010
    Posts
    275
    My Mood
    Cool
    Thanks
    32
    Thanked 54 Times in 47 Posts
    Blog Entries
    2

    Default Re: Seaching an array confusion

    Ok, so I think that you don't even need the catch statement that you have.
    The g.getTitle() part, you may not have that method, but just rename it to whatever your accessor / variable name is, I don't understand why you need a catcfh statement.
    This is the kind of thing I was thinking of for your findGame method.. if there is anything you don't understand, just ask.
    public void findGame()
    {
      // **Bulk of code not included**
      //Get the string, etc.
      int index = searchByTitle(title);
      if(index == -1)
      {
        //No game was found
      }else
      {
        //Game was found, print info about it and stuff
      }
     
    }
    private int searchByTitle(String title)
    {
      Game g;
      for(int counter = 0; counter < games.length; i++)
      {
        //Get the game in the current index
        g = games[counter];
        //Check the title of the game
        if(g.getTitle().equalsIgnoreCase(title))
          return counter;
      }
      return -1;
    }

Similar Threads

  1. CONFUSION - Breadthfirst search
    By clockworkworks in forum Java Theory & Questions
    Replies: 2
    Last Post: April 5th, 2011, 02:37 AM
  2. Package confusion
    By caesius in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 22nd, 2011, 12:08 AM
  3. Method & Class confusion
    By jog98 in forum Object Oriented Programming
    Replies: 8
    Last Post: December 8th, 2010, 11:28 AM
  4. help 2d array confusion
    By Macgrubber in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 29th, 2010, 04:30 PM
  5. ArrayList confusion
    By Stormin in forum Collections and Generics
    Replies: 7
    Last Post: August 13th, 2010, 05:58 PM