I am a beginner JAVA coder, and yes this is a homework assignment for a online class... I am stumped, and cannot get help fast enough when it is 11pm at night :<)


To better explain, I need to be able to have four methods. My first method contains all my variables, so my problem/question is how to call upon all of the variables in my first method so as to use the contents of it in the other three methods created. As of now, each method is independent of each other, so I cannot: Use my Calculations method which requires the variables from my Variables Method!

import javax.swing.JOptionPane;

public class Ch2Lab {
	
	static final double NUM_COMMISSION = 0.02;
	
//	VARIABLES SECTION
	
	public static void Variables()
	{
	 double numStocksBuy;			//Number of stocks purchased
	 double numStocksSell;			//Number of stocks sold
	 double numCostStockBuy;    //Price of each stock when purchased
	 double numCostStockSell;   //Price of each stock when sold
	 double numSumStockBuy;		//Total dollar sum of stock purchased
	 double numSumStockSold;	//Total dollar sum of stock sold
	 double numComPaidBuy;		//Total amount paid in commission when purchased
	 double numComPaidSold;		//Total amount paid in commission when sold
	 double numSumStockComBuy;	//Total sum of stock plus commission when purchased
	 double numSumStockComSell;	//Total sum of stock plus commission when sold
	 double numProfitLoss;		//Value for either profit or loss after buy and sell 
	}
	
	//Section for calculations
	public static void Calculations()
	{	
	numSumStockBuy = numSumStocksBuy * numCostStockBuy;
	numSumStockSold = numSumStocksSell * numCostStockSold;
	numComPaidBuy = ((numStocksBuy * numCostStockBuy) * NUM_COMMISSION);
	numComPaidSold = ((numStocksSold * numCostStockSell) * NUM_COMMISSION);
	numSumStockComBuy = (numComPaidBuy + numSumStockBuy);
	numSumStockComSell = (numComPaidSold + numSumStockSold);
	numProfitLoss = (numSumStockComBuy - numSumStockComSell);
	}
	
	//Section that gets the input from the user using JOptionPane  
	public static Input()
	{
	numStocksBuy = JOptionPane.showInputDialog("Enter the number of" +
			"stocks being purchased: ");
	numCostStockBuy = JOptionPane.showInputDialog("Enter the buy price of" +
			"each stock: ");
	numStocksSell = JOptionPane.showInputDialog("Enter the number of" +
			"stocks being sold: ");
	numCostStockSell = JOptionPane.showInputDialog("Enter the sell price of" +
			"each stock: ");
	}
	
	public static void Output()
	{
	System.out.println("The number of shares of stock purchased: " + numStocksBuy);
	System.out.println("The cost of each share purchased: " + numCostStockBuy);
	System.out.println("Total amount of money paid for the stock: " + numSumStockBuy);
	System.out.println("Amount of commission paid on purchase: " + numComPaidBuy);
	System.out.println("Total price paid including commission: " + numSumStockComBuy);
	System.out.println("The number of shares of stock sold: " + numStocksSell);
	System.out.println("The cost of each share sold: " + numCostStockSell);
	System.out.println("Total amount of money received for the stock: " + numSumStockSold);
	System.out.println("Amount of commission paid on sale: " + numComPaidSold);
	System.out.println("Total price received including commission: " + numSumStockComSell);
	}
	
	public static void main(String[] args) 
	{ 
		Variables();
		Calculations();
		Input();
		Output();
	}

}

Doesn't work like that. Java has the idea that all variables are local. That means that they aren't visible except in the block where they are declared. Period. Only in that one block (or blocks that are contained in it). So to get a value from one function to another, you have to pass it (or something that contains it) as a parameter to the called function. Those parameters are declared as arguments to the function in the outer function block, so they are now visible inside the function, and their values can be accessed in the usual way.

This level of problem is an indication that you are trying to go too fast: You've jumped into a situation that you don't yet understand. Please look again at some of the simple examples that you have for beginning Java programmers. Here's something: http://www.javabeginner.com/ that may be helpful.

So if I move all of my code to be within the public static main class, then I still am not understanding what to put within the paranthesis for each method created within...

So if I have:

public static Variables()
{
double numA;
double numB;
double numC;
}

How would I properly code this? Since I have no examples of this in the book or found online specifically it makes it difficult to understand proper notation.

Look at line 1. You are declaring a static method Variables I have some questions for you:

  • What is the purpose of this function? What does it do? What data does it need to do its work? What results does it make?
  • What parameters will be passed to this method that it can use while it runs? Answer: You have said that this method takes no parameters, because there are none declared within the ()
  • What is the return type of this method? Answer: You did not state that it returns, which you must do, so this method is not syntactically correct.

Until you can answer those questions, you are not going to be able to write a program, or at least not one in Java that makes use of more than one method.

This is not the right place for you to learn the very most basic of Java programming ideas: Daniweb is a place that is good for helping you make your code work or make it work better. It is not appropriate for helping you take the very first steps to begin learning programming.

I can write the whole program without error when I do not use methods. My problem is not understanding how to incorporate a dozen different variables having to do with my particular situation where I have to add and subtract and multiply different variables. So if I am over-simplifying, then my problem lies in my ignorance of not seeing why it has to be so complicated with line after line of duplicated code.

I learn by seeing, not reading basic theory. I understand what your trying to explain, but it does nothing for me visually without seeing it.

So starting over, if I have:

public static double Variables (numA, numB, numC)
{
numA * numB;
return num C;
}

We are not to using object classes so I cannot use that process yet. And my parameters do not hold values until they are input by the user once the program is run, which I assume happens when I call upon the Input.

Line three is still not syntactically correct: What types are numA, numB and numC?

Functions (in java they are all member functions also known as methods) do something. What does this method do? You might as well have written

public static double returnSame(double numC) {
  return numC;
}

All the other stuff you wrote was just noise.

Lets start over for a minute: What is the purpose of your program? What does the program do?. I'll just make something up for now. Lets say the program's job is to be a little tiny calculator that takes two numbers and an operator and prints the results. So how would you write it without methods? You would have a block of code that got the user input, another block that handled addition, another block that handle multiplication, etc. If you want to use methods, then you might write a block of code that gets user input, say, but you would declare it as a method that takes a prompt argument and returns a double, maybe. So public double askForDouble(string prompt) {...} . Then you might have

public static void main(string[] args) {
  double firstNumber = askForDouble("First number please");
  double secondNumber = askForDouble("Second number please");
  string operation = askForOperation("What shall we do with your numbers?")
  double answer = 0.0
  if('+' == operation) {
    answer = doAdd(firstNumber, secondNumber);
  }
  else if ("minus" == operation) { 
    answer = doSubtract(firstNumber,secondNumber);
  }
  // and so forth
  // eventually you would print out the two numbers, the operation and the answer
} // this is the end of main
  • In lines 2 and 3 we call the method askForDouble giving it a parameter, and getting back a value. I showed you what the declaration of that method was, but I didn't write the body.
  • in line 4, we do something similar for a different method
  • in line 5 we declare the variable answewr giving it a default value
  • in lines 6 and 9, we are testing to see what to do with our numbers
  • in lines 7 and 10 we are call two different functions, passing in the two numbers as parameters and getting back a double answer
  • There are going to be a lot more little "else if" blocks that do things for multiply, divide, raise to a power, whatever the calculator should do. And each of them is going to call a method to do the work, and set answer to the return value from that method.
  • finally in the last line of main, we print the answer (which I also didn't show you how to do, because I'm sure you already can)

So, why are many functions better than just a big single function that does it all? Well for a lot of reasons.

  • The easiest to explain is to suppose that my silly askForDouble actually does some hard work of some kind, that takes up maybe 30 lines of code. I used that block of code twice in the silly example, but I only had to write it once: A win.
  • Another reason is that maybe you wrote that method weeks or months ago, and you know just what it does: You don't need to think about it: You just call it and get the correct result.

In every case, the reason you write a function, and use it is because it does something (presumably something useful and interesting); and because you want the results of what it does. Some functions don't return anything: They are called because the do have side effects, like maybe printing something to the screen. In other cases you expect them to give back the results for later use in your program. The first kind are 'void' functions. The second kind has some actual return value.

OKAY, starting over, trying to do this part by part, and starting very small and simple.

Why is this not working:

import javax.swing.JOptionPane;

public class Ch2Lab {
	
	public static void main(String[] args) 
	{ 
		Input();
		System.out.println("You entered: " + getInput);
		
		//This section gets the input from the user using JOptionPane  
		public static Input(getInput)
		{	
		getInput = JOptionPane.showInputDialog("Enter the number of" +
				"stocks being purchased: ");
		}
	}
}

because you've placed one method within another

What is the proper way to call upon them? When I place it all within my main, the JOptionPane becomes a problem. Error after error...

import javax.swing.JOptionPane;

public class Ch2Lab {
	
//	This section gets the input from the user using JOptionPane  
	public static void Input(getInput)
	{	
	JOptionPane.showInputDialog("Enter the number of" +
			"stocks being purchased: ");
	return getInput;
	}
	
	public static void main(String[] args) 
	{ 
		Input();
		System.out.println("You entered: " + getInput);
	}
}

that's because you've placed one method witin another and haven't defined a return type. try it like this:

public static void main(String args[]){
  String input = getInput();
}

public static String getInput(){
  return JOptionPane.showInputDialog("enter a String object");
}

Error: Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error, insert ";" to complete Statement

What you entered is giving an error... and is the same issue I keep having.. is this a code issue or am I having an issue within Eclipse?

please repost
help please!

Post how you incorporated his code please.

OKAY! So here is what I have right now, which compiles and works without issue. My question is how would I make my System.out.println statements be part of their own method, so I could just call on it, with Statement_Methods();

??? I am not sure how to seperate it since it uses variables from within the MAIN method...

import javax.swing.JOptionPane;

public class Ch2Lab
{
	static final double NUM_COMMISSION = 0.02;
	
//FORMULAS USED TO CALCULATE VALUES
	public static double stockSubTotal1(double stockQty, double stockPrice)
		{
		return stockQty * stockPrice;
		}
	
	public static double stockProfitLoss1(double stockSumSell, double stockSumBuy)
	{
		return stockSumSell - stockSumBuy;
	}
	
	public static double stockCommissionBuy1(double stockSumBuy)
	{
		return NUM_COMMISSION * stockSumBuy;
	}
	
	
		public static void main(String[] args)
		{
//VARIABLES FOR USE IN MAIN METHOD
		String strStockQtyBuy;
		String strStockPriceBuy;
		String strStockQtySell; 
		String strStockPriceSell; 
		double dblStockQtyBuy;
		double dblStockPriceBuy;
		double dblStockQtySell;
		double dblStockPriceSell;
		
//		Input Section - Enter details pertaining to quantity purchased and price per stock
		strStockQtyBuy = JOptionPane.showInputDialog("How many stocks to buy: ");
		strStockPriceBuy = JOptionPane.showInputDialog("Price of each stock: ");
		strStockQtySell = JOptionPane.showInputDialog("How many stocks to sell: ");
		strStockPriceSell = JOptionPane.showInputDialog("Price of each stock: ");
		
		dblStockQtyBuy = Double.parseDouble(strStockQtyBuy);
		dblStockPriceBuy = Double.parseDouble(strStockPriceBuy);
		dblStockQtySell = Double.parseDouble(strStockQtySell);
		dblStockPriceSell = Double.parseDouble(strStockPriceSell);
		
		double dblStockSubTotalBuy = stockSubTotal1(dblStockQtyBuy, dblStockPriceBuy);
		double dblStockSubTotalSell = stockSubTotal1(dblStockQtySell, dblStockPriceSell);
		double dblStockCommissionBuy = stockCommissionBuy1(dblStockSubTotalBuy);
		double dblStockCommissionSell = stockCommissionBuy1(dblStockSubTotalSell);
		double dblProfitLoss = (dblStockSubTotalSell + dblStockCommissionSell)-(dblStockSubTotalBuy + dblStockCommissionBuy);
		
//Displays list of values based on the input from user.
		System.out.println("The number of shares of stock purchased: " 			+ dblStockQtyBuy);
		System.out.println("The cost of each share purchased: $" 				+ dblStockPriceBuy);
		System.out.println("The Sub Total thus far is: $" 						+ dblStockSubTotalBuy);
		System.out.println("Amount of commission paid on purchase: $" 			+ dblStockCommissionBuy);
		System.out.println("Total price paid including commission: " 			+ (dblStockSubTotalBuy+dblStockCommissionBuy));
		System.out.println("The number of shares of stock sold: " 				+ dblStockQtySell);
		System.out.println("The cost of each share sold: $" 					+ dblStockPriceSell);
		System.out.println("The Sub Total thus far is: $" 						+ dblStockSubTotalSell);
		System.out.println("Amount of commission paid on sale: " 				+ dblStockCommissionSell);
		System.out.println("Total price received including commission: " 		+ (dblStockSubTotalSell+dblStockCommissionSell));
		System.out.println("The profit/loss from transactions was: $" 			+ dblProfitLoss);
	}
}

You would do what was already suggested, pass paramaters into your method.

public static void main(String[] args)
{
dblStockQtyBuy = Double.parseDouble(strStockQtyBuy);
dblStockPriceBuy = Double.parseDouble(strStockPriceBuy);//etc..
printStuff(dblStockQtyBuy,dblStockPriceBuy);//add the rest of your variables, be sure that the method paramaters have the same amount

}
public static void printStuff(double dblStockQtyBuy,double dblStockPriceBuy)
//add as many paramaters as you have variables you need to use, they dont need to //have the same name as the variables from your main method, as these are local to //the method, but I did this for simplicity sake.
{
System.out.println("The number of shares of stock purchased: " + dblStockQtyBuy);
System.out.println("The cost of each share purchased: $" + dblStockPriceBuy);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.