Results 1 to 20 of 20
  1. #1
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default Pass String[] into method in different class

    Hello, appreciate your help in getting a String array passed into a method in a separate class (ParameterList & Monarch). I was passing the xValues array into Monarch but now I'm using caughtFile which references a text file.

    I'm getting a null pointer exception. Here's my code:

    Java Code:
    public class ParameterList 
    {  
    	//public static String[] xValues = { "Me", "Zebra", "Human", "Elephant", "Chicken" };	
    	public static Integer[] yValues = { new Integer(70), new Integer(40), new Integer(28), new Integer(25), new Integer(9) };;
    	
    	
    	public static String[] readFile(String caughtFilePath) throws IOException
    	{	
    		FileInputStream in = new FileInputStream(caughtFilePath);  //("C:\\xAxis.txt");   // was Array //("C:\\xAxis.txt");
    		BufferedReader br = new BufferedReader(new InputStreamReader(in));
    			
    		//String strLine;
    		String[] myarray;
    		myarray = new String[5];
    									
    		for (int j = 0; j < myarray.length; j++)
    		{
    			myarray[j] = br.readLine();
    			//System.out.println(myarray[j] + "  myarray1");
    			Monarch passArray = new Monarch(myarray, myarray.length); // pass array to Monarch
    		}				
    		in.close();
    		
    		return myarray;
    	}	
    }
    
    
    
    public Monarch(String[] caught, int length)
    	{
    		
    		
    	// Animals - X-axis
    	String[] animals = new String[length];
    	animals =caught; //ParameterList.xValues;
    
    	// Speeds - Y-axis
    	Integer[] speeds = ParameterList.yValues;   
    		
    	// Chart data Model creation
    	ChartDataModel dataModel = new ChartDataModel(new Object[][] {animals, speeds});
    Thanks much for your help

  2. #2
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Java Code:
    for (int j = 0; j < myarray.length; j++)
    		{
    			myarray[j] = br.readLine();
    			//System.out.println(myarray[j] + "  myarray1");
    			Monarch passArray = new Monarch(myarray, myarray.length); // pass array to Monarch
    		}
    Why are you passing the array every iteration of the loop?
    Did you mean:
    Java Code:
    for (int j = 0; j < myarray.length; j++)
    		{
    			myarray[j] = br.readLine();
    			//System.out.println(myarray[j] + "  myarray1");
    		}
    Monarch passArray = new Monarch(myarray, myarray.length); // pass array to Monarch
    ?

  3. #3
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    Good catch, thanks.

    I still don't seem to be passing the array correctly. I'm still getting an unknown source error pointing to

    Java Code:
    //Chart data Model creation
    	ChartDataModel dataModel = new ChartDataModel(new Object[][] {animals, speeds});
    Which is the first place that the animals array is used. In my main class I also have a variable named
    Java Code:
     private static Monarch frame = new Monarch(null,0);
    that builds my JFrame. The only info I'm getting back points to where animals is first used an an error back to where the JFrame is created.

    thanks

  4. #4
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    I did forget one thing. I commented most of the code in the monarch class and put in:
    Java Code:
     
    		String[] test = caught;
    		System.out.println(test);
    and I am passing a value - but it looks like it's only the memory address and not the array. See below:
    [Ljava.lang.String;@13f3789

  5. #5
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    No, you are passing the array. But you cannot print it that way. That only prints the memory address. You must use a for loop for printing.
    Java Code:
    String[] array = {"hi", "there", "!"};
    for(int i=0; i<array.length; i++){
        System.out.println(array[i]);
    }

  6. #6
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    8

    Default

    Quote Originally Posted by quad64bit View Post
    ... You must use a for loop for printing.
    ..
    Or just use the Arrays.toString method.

  7. #7
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by quad64bit View Post
    No, you are passing the array. But you cannot print it that way. That only prints the memory address. You must use a for loop for printing.
    Java Code:
    String[] array = {"hi", "there", "!"};
    for(int i=0; i<array.length; i++){
        System.out.println(array[i]);
    }
    Ahh I see, that would explain the memory address. But when I try to read it in line by line I still get a NullPointerException -this time even if the rest of the class is commented out. So I must have something hosed up.

    But while I was interested in making sure that the array was being passed over my intent was to add the values to 'animals' but I'm still not getting there. Here's the entire class below. It's a 2D plotting tool that my company purchased. Must be pretty close :) thanks!

    Java Code:
    import java.awt.*;
    import javax.swing.JFrame;
    
    import lt.monarch.chart.chart2D.Grid;
    import lt.monarch.chart.chart2D.axis.*;
    import lt.monarch.chart.chart2D.engine.PlaneMapper2D;
    import lt.monarch.chart.chart2D.series.BarSeries;
    import lt.monarch.chart.engine.ChartObject;
    import lt.monarch.chart.legend.Legend;
    import lt.monarch.chart.mapper.LabelAxisMapper;
    import lt.monarch.chart.mapper.MathAxisMapper;
    import lt.monarch.chart.models.ChartDataModel;
    import lt.monarch.chart.style.enums.*;
    import lt.monarch.chart.style.tags.AxisTextPaintTags;
    import lt.monarch.chart.swing.JChartPanel;
    import lt.monarch.chart.view.LabeledChart;
    
    
    @SuppressWarnings("serial")
    public class Monarch extends JFrame 
    {		
    	public Monarch(String[] caught, int length)
    	{	
    	//	String[] test = caught;
    	//	System.out.println(test);
    				
    	// Animals - X-axis
    	String[] animals = new String[length];
    	animals = caught; //ParameterList.xValues;
    	
    	for(int i = 0; i < caught.length; i ++)
    	{
    		animals[i] = caught[i];
    		System.out.println(animals[i]);
    	}				
    		// Speeds - Y-axis
    		Integer[] speeds = ParameterList.yValues;   
    		
    	// Chart data Model creation
    	ChartDataModel dataModel = new ChartDataModel(new Object[][] {animals, speeds});
    	// Maps integers from 0 to 80 on to the y axis
    	MathAxisMapper yMapper = new MathAxisMapper(0, 80);
    	// Maps labels on to the x axis
    	LabelAxisMapper xMapper = new LabelAxisMapper(animals);
    	// Setting Bars
    	BarSeries bars = new BarSeries(dataModel, xMapper, yMapper);
    	// Setting bars' background and foreground colors
    	bars.style.setBackground(new Color(30,90,255));
    	bars.style.setForeground(new Color(30,90,255));
    	// Setting BarSeries title which will show up in legend
    	bars.setName("Speed");
    	// Setting X-axis
    	Axis2DX axisX = new Axis2DX(xMapper);
    	// Setting X-axis title which will be shown on chart
    	axisX.setTitle("Animal types");
    	// Setting X-axis title position
    	axisX.getTitleSettings().setTitlePosition(TitlePosition.BELOW);
    	// Setting X-axis fonts
    	axisX.getTextStyle().setFont(AxisTextPaintTags.LABEL, new Font("dialog", Font.PLAIN, 10));
    	axisX.style.setFont("title", new Font("dialog", Font.PLAIN, 15));
    	// Setting Y-axis
    	Axis2DY axisY = new Axis2DY(yMapper);
    	// Setting Y-axis title which will be shown on chart
    	axisY.setTitle("Speed, Mph");
    	// Setting Y-axis title position
    	axisY.getTitleSettings().setTitlePosition(TitlePosition.BELOW);
    	// Setting Y-axis fonts
    	axisY.getTextStyle().setFont(AxisTextPaintTags.LABEL, new Font("dialog", Font.PLAIN, 10));
    	axisY.style.setFont("title", new Font("dialog", Font.PLAIN, 15));
    	// Horizontal grid creation
    	// We do not specify the x axis because we want only horizontal lines to be painted.
    	Grid grid = new Grid(new PlaneMapper2D(), null, yMapper);
    	// Chart object creation and configuration
    	Chart2D chart = new Chart2D();
    	// Setting objects which will be drawn
    	chart.setObjects(new ChartObject[] { grid, bars});
    	// Setting chart's axis
    	chart.setXAxis(axisX);
    	chart.setYAxis(axisY);
    	// Setting legend
    	Legend legend = new Legend(chart);
    	// Setting legend's fonts and colors
    	legend.style.setFont("legend", new Font("dialog", Font.PLAIN, 8));
    	legend.style.setBackground(Color.WHITE);
    	// Setting Main chart
    	LabeledChart topChart = new LabeledChart(chart);
    	// Setting title
    	topChart.setTitle("Animal Speeds");
    	// Setting legend's position on chart
    	topChart.setBottomView(legend);	
    	getContentPane().add(BorderLayout.CENTER, new JChartPanel(topChart));
    	}		
    	public void MonarchOutput()
    	{
    		//return Monarch;
    	}	
    }
    thanks guys

  8. #8
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    r035198x is correct, Array.toString(someArray) is also good if you don't need special formatting and excellent for testing.

    Let me ask you this, do any of the elements print when you run the code? Like, strings 0 through 5 print, but THEN you get a null pointer? Or does the null pointer happen immediately before any printing has happened?

    In the latter case, either your loop is seeking too far, or the array is missing an element at the end. In either case, you need to look at the loops filling/reading the array to make sure they are printing everything.

    Secondly
    Java Code:
    String[] animals = new String[length];
    	animals = caught; //ParameterList.xValues;
    	
    	for(int i = 0; i < caught.length; i ++)
    	{
    		animals[i] = caught[i];
    		System.out.println(animals[i]);
    	}
    Woah there, way too much happening. This would be fine:
    Java Code:
    String[] animals = caught;
    for(int i=0; i<animals.length; i++)
        System.out.println(animals[i]);
    You're doing a LOT of unneeded assignment in your snippet.

    Start with that, and double check the loop that fills the array initially. Does your IDE have a debugger? Eclipse, Netbeans, even BlueJ do -- I suggest you step through the code starting with filling the first array, and see if the array ever gets filled with anything to begin with.

  9. #9
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    The null pointer happens before the array is read out. I've got to run out for dinner, I'll try that as soon as I get back. I've been working in VS but am new to working in Eclipse and don't have a proficient programming background. Supposed to get a debugger tutorial on Monday :rolleyes:

    I do appreciate your help

  10. #10
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    I've been looking at the debugger and it just isn't intuitive enought for me. I've set a couple break points but I can't figure out how to walk thru


    You alluded to it above that unless we can confirm the array is being populated initially it's hard to move beyond this first step. Aside from that you've helped me a lot. I do appreciate it but unless you have another thought I don't think I'm using your time well anymore. thanks much, I'll see you around the forum

  11. #11
    quad64bit's Avatar
    quad64bit is offline Moderator
    Join Date
    Jul 2009
    Location
    VA
    Posts
    1,323
    Rep Power
    7

    Default

    Ok here is another thought.

    Put System.out.println()'s everywhere. Inside the loops. After the loops. before. etc...
    See if you can figure out where the data is going missing. Its like manual debugging :D

  12. #12
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by quad64bit View Post
    Ok here is another thought.

    Put System.out.println()'s everywhere. Inside the loops. After the loops. before. etc...
    See if you can figure out where the data is going missing. Its like manual debugging :D
    Yeah man!

    I had been doing a little of that but I'll put them everywhere in the morning

  13. #13
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    Well, I never was able to get the value passed between classes even though setting println's everwhere I was able to see that I was passing values between classes and everything should have worked but I got it working in one class.

    One thing that I haven't been able to get to display is the JButtons along with the chart. If anyone has any thoughts that would be cool.

    If not, I learned how to use the debugger somewhat and got a lot of take aways; so thanks for the help.
    Java Code:
    public class Main extends JFrame    
    {		 		
    	private JPanel m_MainPanel;	
    	private JButton m_PlotButton; 
    	private JButton m_ExitButton;	
    	private JMenuBar m_MenuBar; // MENUBAR.java	
    	private JButton m_MonarchExitButton;
    	private String pathToReadFileMethod;
    	private String[] catchFromReadFile;
    	private String[] passToMonarch;
    		
    	private String GetYFromFile;
    	private String[] yFromReadFile;
    	private Integer[] intArrayFromReadFile;
    	
    	// Chart object creation and configuration
    	//private JChartPanel graph;	
    
    	public Main() throws IOException
    	{	
    		//Check the Format of yValue Array		
    		/*for(int i=0; i<yValues.length; i++)
    		{
    			System.out.println(yValues[i] + " in the yValues");
    		}*/
    				
    		m_MainPanel = new JPanel();
    		m_MainPanel.setLayout(null);  
    		m_MainPanel.setSize(this.getContentPane().getSize().width, this.getContentPane().getSize().height);
    		m_MainPanel.setLocation(0,0);
    		m_MainPanel.setBackground(Color.LIGHT_GRAY);	
    		//this.getContentPane().add(m_MainPanel);
    
    		//View Plot Button
    		m_PlotButton = new JButton("Generate Plot");
    		m_PlotButton.setSize(125, 20);
    		m_PlotButton.setLocation(410,390);
    		m_PlotButton.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    		m_PlotButton.addActionListener(
    				new ActionListener()
    				{
    					public void actionPerformed(ActionEvent e)
    					{
    							m_MainPanel.repaint();
    						}
    					}
    				);
    		m_MainPanel.add(m_PlotButton);
    
    		//Exit Button on JPanel.Form
    		m_ExitButton = new JButton("Exit");
    		m_ExitButton.setSize(75,20);
    		m_ExitButton.setLocation(540, 390);
    		m_ExitButton.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    		m_ExitButton.addActionListener(
    				new ActionListener()
    				{
    					public void actionPerformed(ActionEvent e)
    					{
    						System.exit(0);					
    					}
    				});
    		m_MainPanel.add(m_ExitButton);
    		
    		//Exit Button on JFrame.Frame
    		m_MonarchExitButton = new JButton("Exit");
    		m_MonarchExitButton.setSize(75,20);
    		m_MonarchExitButton.setLocation(540, 390);
    		m_MonarchExitButton.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
    		m_MonarchExitButton.addActionListener(
    				new ActionListener()
    				{
    					public void actionPerformed(ActionEvent e)
    					{
    					}
    				});
    		getContentPane().add(BorderLayout.SOUTH, m_MainPanel);
    		
    		/** Start: Get xValues  **/
    		// passToMonarch is the String[] after being distilled by the readFile Method
    		passToMonarch = catchFromReadFile;
    		
    		// Pass File Path into ReadFile Method
    		pathToReadFileMethod= ("C:\\Eclipse\\2DGraph_BarChart\\InputFiles\\xValues.txt");
    			if(pathToReadFileMethod != null)
    				{
    					readFile(pathToReadFileMethod);
    				}
    			else
    				{
    					JOptionPane.showMessageDialog(m_MainPanel, "Check X & Y File Presence", "Error", JOptionPane.ERROR_MESSAGE);
    				}
    				
    		// Catch String Array from readFile method
    		catchFromReadFile= readFile(pathToReadFileMethod); //capture return from readFile
    		System.out.println(catchFromReadFile + " catchArray should be a memory location");
    		
    		/**Start New YValues**/
    		//File Path to Y-Axis
    		GetYFromFile = ("C:\\Eclipse\\2DGraph_BarChart\\InputFiles\\yValues.txt");
    			if(GetYFromFile != null)
    				{
    					readFile(GetYFromFile);	
    				}
    			else{
    					JOptionPane.showMessageDialog(m_MainPanel, "Check X & Y File Presence", "Error", JOptionPane.ERROR_MESSAGE);
    				}
    				
    		//Pass GetYFromFile into the readFile method
    		yFromReadFile = readFile(GetYFromFile);
    				
    		convertStringArraytoIntArray(yFromReadFile); 	
    				
    		intArrayFromReadFile = convertStringArraytoIntArray(yFromReadFile);		
    		System.out.println(yFromReadFile + "What do I say");
    			
    		// Build Parameter List and Pass String[] / Integer[] to Monarch Method		
    		passToMonarch = Monarch(catchFromReadFile, intArrayFromReadFile);  //Takes the String value handled in the ReadFile Method and also passes in the Integer From convertStringArraytoIntArray 
    		System.out.println(passToMonarch + "did this fail");
    	
    		//MenuBar
    		m_MenuBar = new JMenuBar();
    		this.setJMenuBar(m_MenuBar);
    
    		//  JFrame.Form visible
    		setVisible(true);	 
    		this.repaint();
    }	
    	
    	public Integer[] convertStringArraytoIntArray(String[] sarray)
    	{		
    		sarray = yFromReadFile;    
    		Integer intarray[] = null;
    		
    		if (sarray != null) 
    		{
    			intarray = new Integer[sarray.length];
    			for (int i = 0; i < sarray.length; i++) 
    			{
    				intarray[i] = Integer.parseInt(sarray[i]);
    				System.out.println(intarray[i] + "   - Caught File in ConvertStringArraytoIntArray");
    			}
    			//return intarray;
    			}
    			//return null;
    		return intarray;
    	} 
    	
    	//readFile grabs String, reads file and returns String Array
    public String[] readFile(String caughtFilePath) throws IOException
    	{	
    		FileInputStream in = new FileInputStream(caughtFilePath);
    		BufferedReader br = new BufferedReader(new InputStreamReader(in));
    		
    		String[] myarray;
    		myarray = new String[5];
    	
    		for (int j = 0; j < myarray.length; j++)
    		{
    			myarray[j] = br.readLine();
    			System.out.println(myarray[j] + " reading");
    		}	    		
    		in.close();
    	
    		return myarray;
    	}	
    
    private String[] Monarch(String[] arrayInput, Integer[] intArrayInput)
    {	
    	String[] animals = arrayInput; // xValues;
    	System.out.println(animals);
    	
    	// Speeds - Y-axis
    	Integer[] speeds = intArrayInput; //yValues 
    	
    	if (animals != null)
    	{			
    		//for(int i=0; i<animals.length; i++)
    		//{
    			//System.out.println(animals[i] + " in the Monarch Loop");
    //		System.out.println(animals + " in the Monarch Loop");
    		//}
    	
    		// Chart data Model creation
    		// * * Chart Data From Vendor Purchased Software * * //
    		
    		getContentPane().add(BorderLayout.NORTH, new JChartPanel(topChart));
    		//m_MainPanel.add(new JChartPanel(topChart));		
    	}
    	else
    		{		
    			System.out.println("Failed the Monarch Loop");
    			System.exit(0);	
    		}
    	
    	return (arrayInput);
    }
    
    public static void main(String[]args) throws IOException
    	{	
    	
     		//Main Form
    		Main form = new Main(); 
    		form.setSize(640, 480); 
    		form.setLocation(100,100);	 
    		form.setTitle("Space & Missile Defense Command - AMOR");	
    		form.setDefaultCloseOperation(EXIT_ON_CLOSE);
    		
    		
    	}		
    }

  14. #14
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Not a clue on your JButtons, but a quick note on the Eclipse debugger (which is awesome if you know how to use it, especially for multi-threaded programs - just be sure to name your threads)

    The breakpoints let you see what values your variables hold. Thats all any debugger can really do as far as I know, though I believe there may be other features I don't know about yet. Personally, I combine println statements with breakpoints, printlns for when I'm only using a single variable, breakpoints for anything more than 4, because 4 printlns one after the other get cluttered.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  15. #15
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by Singing Boyo View Post
    Not a clue on your JButtons, but a quick note on the Eclipse debugger (which is awesome if you know how to use it, especially for multi-threaded programs - just be sure to name your threads)

    The breakpoints let you see what values your variables hold. Thats all any debugger can really do as far as I know, though I believe there may be other features I don't know about yet. Personally, I combine println statements with breakpoints, printlns for when I'm only using a single variable, breakpoints for anything more than 4, because 4 printlns one after the other get cluttered.
    In Visual Studios there is a watch and locals window available while debugging. Watch is similar to Eclipse where you can drag your variable down to the Expressions window. Locals would be the same as if you right click on the variable and choose Inspect. Is there a way that I can just hover over the variable instead of having to right click every time?

    And if anyone knows about the JButtons that would be sweet

  16. #16
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default

    Quote Originally Posted by Swankee View Post
    Is there a way that I can just hover over the variable instead of having to right click every time?
    I get the values when I hover over the variable in the code window...do you not get that?

  17. #17
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    I get the values when I hover over the variable in the code window...do you not get that?
    Unfortunately not, I get the class that the variable belongs to. If I hover over a String I get:

    String varname - ArraysandIOMain.(String[])

  18. #18
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

    Default

    I'm on 3.4.2, if that helps...but what you just posted is what it puts up before the variable has been initialised (ie before your code has actually reached the point where varname has been declared).

  19. #19
    Swankee is offline Member
    Join Date
    Sep 2009
    Posts
    14
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    I'm on 3.4.2, if that helps...but what you just posted is what it puts up before the variable has been initialised (ie before your code has actually reached the point where varname has been declared).
    arghh, of course it worked out that way for me. Thanks :D

  20. #20
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,006
    Rep Power
    20

Similar Threads

  1. Replies: 7
    Last Post: 05-06-2009, 12:42 PM
  2. Replies: 4
    Last Post: 03-03-2009, 09:39 AM
  3. unable to pass value from one class to another
    By ddatta8 in forum New To Java
    Replies: 14
    Last Post: 12-28-2008, 02:24 PM
  4. Replies: 1
    Last Post: 08-22-2008, 06:28 PM
  5. Replies: 1
    Last Post: 08-03-2007, 10:52 AM

Posting Permissions

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