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 14 of 14

Thread: Trouble inputting values into a 2-dimensional array

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    15
    My Mood
    Confused
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Trouble inputting values into a 2-dimensional array

    Hey guys I'm trying to input values into a 2 dimensional array in a program I am doing for school. My code is as follows:

    import java.util.Arrays;
    import java.util.Scanner;
    public class Location {
    	private int row;
    	private int column;
    	private int[][] array = new int[row][column];
    	public static void main(String[] args) {
    		Scanner numberInput = new Scanner(System.in);
    		System.out.println("Enter the number of rows and columns of the array: ");
    		int row = numberInput.nextInt();
    		int column = numberInput.nextInt();
    		Location l1 = new Location(row, column);
    		System.out.println("Please enter the array elements: ");
    		for (int r = 0; r < l1.array.length; r++){
    			for (int c = 0; c < l1.array[r].length; c++)
    				l1.array[r][c] = numberInput.nextInt();
     
    		}
     
     
     
     
    	}//end main
     
    	Location(){}//end constructor
     
    	Location(int row, int column){
    		this.row = row;
    		this.column = column;
    	}//end arg constructor
     
    	public double getMax(){
    		double max = -10000000;
    		for (int i = 0; i < array.length; i++){
    			for (int j = 0; j < array[i].length; j++){
     
    				if (array[i][j] > max)
     
    					max = array[i][j];
    			}
    	}
    		return max;
    	}
     
    	public Location locateLargest(double[][] x){
     
    		for (int i = 0; i < array.length; i++){
    			for (int j = 0; j < array.length; j++){
    				if (array[i][j] == getMax())
    					return x;
    			}
    		}
    	}//end locateLargest()
     
    	public int getRow(){
    		return this.row;
    	}//end getRow()
     
    	public int getColumn(){
    		return this.column;
    	}//end getColumn()
     
    }//end class

    When I try to input each individual value into the array using the for loop, It terminates right there. That means that its not getting my array lengths and I don't know why. Any help would be appreciated.


  2. #2
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    When you initialized the array, it took the values that you had right before that, which, when unspecified, are 0.

    private int row;
    private int column;

    private int[][] array = new int[row][column];

    Why don't you put the array in the constructor and make the array a class variable?


    private int[][] array;
     
    .........
     
    Location(int row, int column){
    		this.row = row;
    		this.column = column;
              array = new int[row][column];
    	}//end arg constructor

  3. The Following User Says Thank You to GoodbyeWorld For This Useful Post:

    thegorila78 (November 16th, 2013)

  4. #3
    Junior Member
    Join Date
    Oct 2013
    Posts
    15
    My Mood
    Confused
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    Thanks for the reply man I understand what I did wrong now and fixed it. I also have another question though. Another part of my assignment is to find the coordinates of the max value or locate where in the array it is and display it. As you can see in my code above I am trying to return x but it is giving me an error that says I cannot convert from type location to double[][]. In my directions it says to use a toString method to display the coordinates as a string but I am completely oblivious as to how a toString method even works. Also, I am not sure if my getLocation() code is even correct for returning the location.. Any help would be greatly appreciated.

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    For further help with your program, show your updated code. Guessing what needs to be done is not helpful.

    The toString() method exists in the Ojbect class and can/should be overridden by any class in order to customize how that object is displayed as a String. When an instance of the object is encountered as part of a String, the object's toString() method is called. For example, the following statement includes a Location instance called "location":

    System.out.println( "This is the location: " + location );

    When the output is built, the method Location.toString() will be called automatically, so the ultimate result is:

    System.out.println( "This is the location: " + location.toString() );

    So your assignment, should you choose to accept it, is to write a toString() method for your Location class that presents the location as a String. The signature for the toString() method is:

    public String toString()

  6. #5
    Junior Member
    Join Date
    Oct 2013
    Posts
    15
    My Mood
    Confused
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    Alright my updated code is:

    import java.util.Arrays;
    import java.util.Scanner;
    public class Location {
    	private int row;
    	private int column;
    	private int[][] array;
    	public static void main(String[] args) {
    		Scanner numberInput = new Scanner(System.in);
    		System.out.println("Enter the number of rows and columns of the array: ");
    		int row = numberInput.nextInt();
    		int column = numberInput.nextInt();
    		Location l1 = new Location(row, column);
    		System.out.println("Please enter the array elements: ");
    		for (int r = 0; r < l1.array.length; r++){
    			for (int c = 0; c < l1.array[r].length; c++){
    				l1.array[r][c] = numberInput.nextInt();
    			}//end nested loop
     
    		}//end for loop
     
     
     
     
     
    	}//end main
     
    	Location(){}//end constructor
     
    	Location(int row, int column){
    		this.row = row;
    		this.column = column;
    		array = new int[row][column];
    	}//end arg constructor
     
    	public double getMax(){
    		double max = -10000000;
    		for (int i = 0; i < array.length; i++){
    			for (int j = 0; j < array[i].length; j++){
     
    				if (array[i][j] > max)
     
    					max = array[i][j];
    			}
    	}
    		return max;
    	}
     
    	public Location locateLargest(double[][] x){
     
    		for (int i = 0; i < array.length; i++){
    			for (int j = 0; j < array.length; j++){
    				if (array[i][j] == getMax())
    					return i;
    			}
    		}
    	}//end locateLargest()
     
    	public int getRow(){
    		return this.row;
    	}//end getRow()
     
    	public int getColumn(){
    		return this.column;
    	}//end getColumn()
     
    }//end class

    I'm sorry I didn't ask the right question. The real question I was trying to get at was how I can fix my code in the locateLargest method so I can return the coordinates of the largest number in my array. I am also not sure what I should put into the argument (double[][] x). When I try to return something with my current code it says that there is a type mismatch and I can only return something that is of the type Location, not double. Thanks in advance.

  7. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    You're on the right path, but you've complicated the answer by loading up the Location class with attributes that have nothing to do with a Location. The class Location should be separate, containing only the fields necessary to specify a location object, in this case x and y, but you could expand Location for any sized array. Then the method locateLargest() would return a Location object as already specified, made up of the x/y pair, something like:

    return new Location( i, j );

    Where i and j have been identified as the coordinates of the largest element in the argument array. So, simplify the class Location. Strip out the main() method and other parts of it that are used to test it and put those in another driver or test class.

    This exercise is an example of one possible answer to the oft-asked question, "How can I return more than one value from a method?"

  8. #7
    Junior Member
    Join Date
    Oct 2013
    Posts
    15
    My Mood
    Confused
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    I think I get what you're saying but I'm still kinda lost. So, if I make a new class just for Location, should I keep both the constructors in the old class or put them in the new one? Also, which class should I put the private ints in? Thanks for the help btw.

  9. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    I've outlined how I imagine it could look below. Note that both classes are public so would be in separate files, but the Location class could be in the same file as LocationTester by removing the public access modifier. You can start by moving much of your code from your existing main() method into the outline below.
    // class LocationTester is a class to create/use/test Location objects
    public class LocationTester
    {
        public static void main( String[] args )
        {
            // code to create/use/test Location objects, probably
            // starting by filling an array with Location objects
     
        }//end main
     
        public static Location findLargestLocation( int[][] intArray )
        {
            // code to find the coordinates of the largest
            // value in the argument array, intArray, then
            // used to return a Location object
     
            return new Location( row, col );
     
        } // end method findLargestLocation()
     
    } // end class LocationTester
     
    // class Location specifies the location in a 2D grid by the coordinates
    // row / column 
    public class Location
    {
        private int row;
        private int column;
     
        public Location( int row, int column )
        {
            this.row = row;
            this.column = column;
        }
     
        // then getters, setters, etc. as appropriate for a Location
        // (can't think of any)
     
    } // end class Location
    Also note that your code to fill the array is not quite right. The array is first declared with:

    int[][] array = new int[row][column];

    Inside the nested for loop, the array will be filled:

    array[r][c] = numberInput.nextInt();

    Hope this helps, but don't hesitate to ask more questions if you need to.

  10. #9
    Junior Member
    Join Date
    Oct 2013
    Posts
    15
    My Mood
    Confused
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    Thanks for the reply. My updated code is:

    import java.util.Scanner;
     
    public class LocationTest {
     
    	public static void main(String[] args) {
    		Scanner numberInput = new Scanner(System.in);
    		System.out.println("Enter the number of rows and columns of the array: ");
    		int row = numberInput.nextInt();
    		int column = numberInput.nextInt();
    		Location l1 = new Location(row, column);
    		row = l1.getRow();
    		column = l1.getColumn();
    		int[][] array = new int[l1.getRow()][l1.getColumn()];
    		System.out.println("Please enter the array elements: ");
    		for (int r = 0; r < array.length; r++){
    			for (int c = 0; c < array[r].length; c++){
    				array[r][c] = numberInput.nextInt();
    			}//end nested loop
     
    		}//end for loop
    		System.out.println(getMax(array));
    	}
    		public static int getMax(int[][] x){
    			int max = -10000000;
    			for (int i = 0; i < x.length; i++){
    				for (int j = 0; j < x[i].length; j++){
     
    					if (x[i][j] > max)
     
    						max = x[i][j];
    				}
    		}
    			return max;
    		}
     
     
    		public Location locateLargest(int[][] x){ 
    			for (int i = 0; i < x.length; i++){
    				for (int j = 0; j < x.length; j++){
    					if (x[i][j] == getMax(x))
    						return new Location(i,j);
    				}
    			}
    		}//end locateLargest()
     
     
     
    }
    class Location {
    	private int row;
    	private int column;
     
     
    	Location(){}//end constructor
     
    	Location(int row, int column){
    		this.row = row;
    		this.column = column;
    	}//end arg constructor
     
    	public int getRow(){
    		return this.row;
    	}
     
    	public int getColumn(){
    		return this.column;
    	}
     
    }

    Now I am not sure if I should make the array a class variable or just keep it in the main method. Also, I am getting an error in the first line of my location class that says: The type location is already defined. I am also still trying to figure out how to return the location of the max as I am also getting an error in the method declaration of locateLargest that says: The method must return a result of type Location.

    Thanks in advance I know I must be getting annoying.

  11. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    You must have another Location class (the original?) still defined in the same package. Rename it, move it, delete it, whatever you want to do.

    Where to define the array variable is purely up to you. Technically, it makes no difference. As a more mature/seasoned coder, you won't have more than a few lines in the main() method that call methods of another class, so very few (if any) static variables (class variables) will be required. That you're not there yet is understandable.

    An appropriate return must exist for every possible path in a method with a return type other than void. In the case of the locateLargest() method, if the if() condition is never true, the return statement will never be executed, so the error is shown. An option is to include a default "return null;" statement as needed, handling the null as appropriate at the calling end.

    You should not call getMax( x ) for each possible comparison of the array values in locateLargest(). Instead, assign the getMax( x ) result to a variable maxValue (or a name of your choice) before beginning the for loops, and compare each value in the array to that. There are probably other efficiencies that could be gained, but I'll leave those to you.

    There's a constant, Integer.MIN_VALUE, available for use as the smallest int possible.

    Close your Scanner object. Indent your code properly. Delete extra blank lines that serve no purpose.

  12. The Following User Says Thank You to GregBrannon For This Useful Post:

    thegorila78 (November 17th, 2013)

  13. #11
    Junior Member
    Join Date
    Oct 2013
    Posts
    15
    My Mood
    Confused
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    Ok I made the changes you said I should accept now I'm getting a different error in the method header of locateLargest which is :The method getMax(int[][]) in the type Location is not applicable for the arguments (). My updated code for the method is as follows:
    public Location locateLargest(int[][] x){ 
    			int maxValue = getMax(x);
    			for (int i = 0; i < x.length; i++){
    				for (int j = 0; j < x.length; j++)
    					if (x[i][j] == maxValue)
    						return new Location(i,j);
    			}
    			return null;
    		}

    Thanks in advance.

  14. #12
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    Save and recompile. The error doesn't occur here and doesn't make sense, because you're not calling getMax() with no arguments.

  15. The Following User Says Thank You to GregBrannon For This Useful Post:

    thegorila78 (November 17th, 2013)

  16. #13
    Junior Member
    Join Date
    Oct 2013
    Posts
    15
    My Mood
    Confused
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    You have been a real help man. I have one final problem with the toString method. I have no idea what to put in the return statement. When I input i and j, it says they cannot be resolved to a variable. Do I just call the locateLargest method in the toString? Sorry if I sound like a total noob because I am haha. Thanks in advance.

  17. #14
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Trouble inputting values into a 2-dimensional array

    This is something you should play around with and figure out. Start with a Location.toString() method that simply returns the String, "My brother is a lobster," and see how that is used when the toString() method is applied by default as I described in post #4. Then, because the state of your brother has nothing to do with the assignment, consider how you might change it to be something useful.

Similar Threads

  1. Create two dimensional array from a one dimensional array
    By Kristenw17 in forum Collections and Generics
    Replies: 1
    Last Post: April 9th, 2013, 07:51 PM
  2. Converting Two dimensional array into an Array list
    By NewbieJavaProgrammer in forum Object Oriented Programming
    Replies: 11
    Last Post: September 29th, 2012, 04:23 PM
  3. Read A File and Store Values into a 2-Dimensional Integer Array?
    By Kimimaru in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 9th, 2011, 09:13 PM
  4. need help inputting values into an array
    By pds8475 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 22nd, 2011, 09:47 PM
  5. Having trouble insert/sorting array values w/ binary searching.
    By bh-chobo in forum Collections and Generics
    Replies: 4
    Last Post: October 8th, 2009, 02:38 AM