![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Nov 2007
Posts: 4
Rep Power: 0
![]() |
retaining values in methods
Hello,
I'm pretty new to OOP and Jave and have ran into an issue on how to code some logic. I have a method that's needing to hold a local variables value upon different calls. I have tried this code but realize that Java can only use static keyword for classes. ( I think i have the code right, my code came off of a different computer that does not have internet access. I think I have remembered it correctly though.) private float proc(int a, int b, boolean state){
if(state == true){
//do processing here
static int complete = 1;
return result;
}else{
if(complete != 1){
//do same processing here
}
// more processing
return result;
}private float proc(int a, int b, boolean state){
Integer completed;
if(state == true){
//do processing here
completed = 1;
return result;
}else{
if(completed != 1){
//do same processing here
}
// more processing
return result;
} |
|
|
|
|
|
#2 |
|
Expert Programmer
|
Re: retaining values in methods
You can declare the variable outside the method as a private class variable:
private int complete;
...
private float proc(int a, int b, boolean state) { ... } |
|
|
|
|
|
#3 |
|
12 years old
Join Date: Nov 2007
Posts: 94
Rep Power: 1
![]() |
Re: retaining values in methods
private float proc(int a, int b, boolean state) {
int completed = 0;
if(state) {
//do processing here
completed = 1;
return result; //not defined???
}
//no need for the else block or completed value check, if it was state it would have returned, if it was not it would have gone here.
//do same processing
//more processing
return result; //not defined???
}private static int complete; And nightFix, the error is because in Java, fields aren't auto initialized like in C++, you need to declare complete as a new Integer object type with the value as the constructor argument; but you should instead just declare it as a primitive 'int'. Primitives to Object types is not an optimization. |
|
|
|
|
|
#4 |
|
Newbie
Join Date: Nov 2007
Posts: 4
Rep Power: 0
![]() |
Re: retaining values in methods
Hey,
thank you for the input and quick responses. Null you are right I don't need an else there! Though I don't know if that affects processing time. I was using an Integer object rather than an int declaration because I was told that you can't pass primitive data types by reference nor can you get them to retain their value with different calls unless they are an object. Like I said I'm new to this and am probably needing to review my private vs public uses. Well I'm in a hurry right now but I still haven't got this code working. Hold the posts till I can get some code up later today. I appreciate the replies though and setting me on the right track. Thanks a lot. |
|
|
|
|
|
#5 |
|
Battle Programmer
Join Date: Feb 2006
Location: Bellevue, WA, USA
Posts: 763
Rep Power: 3
![]() |
Re: retaining values in methods
Slightly incorrect. C++ doesn't initialize fields/variables, but Java will initialize primitives to 0 and objects to null. C++ will call the default constructor for an object at instantiation if no other constructor is given (and probably for a class field as well - they're kinda weird) but a pointer to an object is a primitive and will not be initialized; the default constructor will likely initialize the variables, but that's up to the class' author.
__________________
<insert disclaimer here> <insert shameless plug for Visual Studio here> |
|
|
|
|
|
#6 |
|
Newbie
Join Date: Nov 2007
Posts: 4
Rep Power: 0
![]() |
Re: retaining values in methods
OK.
Sorry it took me so long to get back to you all. Well I almost have my code working and believe I am using my access modifiers correctly but have never really used them before so if anyone picks up on a better way to do this than it will be considered. My problem now, is that when my clear() method is called it throws an exception. I've narrowed it down to the my JTextFields you will see identified as txtXXXX. I have a feeling this is probably something simple but for some reason I'm not seeing it. Exception handling with Java is pretty new to me as well. I think I'm posting enough code to make it interpretable. Thanks for bearing with me. public class PointOfSale extends JFrame implements ActionListener, ItemListener{
//class variables
JTextArea viewport1 = new JTextArea(3,20);
JTextPane viewport2 = new JTextPane();
int quant;
float price;
String item;
//static vars for ctrl break and accumulated total
static String nameHolder = "";
static float total;
public void actionPerformed(ActionEvent e){
try{
int index;
int id;
int quant;
String arg = e.getActionCommand();
String name = txtLname.getText();
quant = comboQty.getSelectedIndex() + 1;
id = Integer.parseInt(txtID.getText());
index = furnCombo.getSelectedIndex();
item = catalog[index];
price = Float.valueOf(txtPrice.getText());
if(e.getSource() == btnPCheck || arg == "Price Check"){
price = proc(quant, index, false);
}
if(e.getSource() == btnProc || arg == "Process"){
if(name.compareTo("") == 0 || price < 1) throw new NumberFormatException();
viewport1.setText("");
if(name.compareTo(nameHolder) != 0){
total = 0;
}
price = proc(quant, index, true);
nameHolder = name;
total += price;
clear();
}
if(e.getSource() == btnFinal){
viewport1.setText("");
viewport2.setText("");
JOptionPane.showMessageDialog(null, "Confirm total: " + total, "Confirm", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == btnClear || arg == "Clear"){
clear();
}
if(e.getSource() == btnSysClear || arg == "SysClear"){
clear();
}
if(e.getSource() == btnExit || arg == "Exit")
System.exit(0);
}
catch(NumberFormatException nFx){
JOptionPane.showMessageDialog(null, "You have entered an incorrect value.", "Format Error", JOptionPane.ERROR_MESSAGE);
}
catch(Exception x){
JOptionPane.showMessageDialog(null, "An Error has occured.");
}
finally{
System.out.println("exception cleanup");
}
}//end actionPerformed
private float carryCharge;
private int pCheckFlag;
private float proc(int quant, int itemKey, boolean taxInc){
float tax;
if(taxInc == false){
float discount = 100 * (discountKey[itemKey]);
float discountAmt = (float) price * (discountKey[itemKey]);
price = (price * quant) - discountAmt;
print2viewport1(discount, discountAmt, price);
carryCharge = price;
pCheckFlag = 1;
return price;
}else{
if(pCheckFlag != 1){
price = proc(quant, itemKey, false);
viewport1.setText("");
}
tax = getTax();
price = carryCharge + (carryCharge * tax);
viewport2 = print2viewport2();
pCheckFlag = 0;
return carryCharge;
}
}//end proc
private void clear(){
//txtfields throwing errors
txtID.setText("");
txtPrice.setText("");
//txtLname.setText("");
furnCombo.setSelectedIndex(0);
comboQty.setSelectedIndex(0);
rbTax[5].setSelected(true);
viewport1.setText("");
}//end clear |
|
|
|
|
|
#7 |
|
Newbie
Join Date: Nov 2007
Posts: 4
Rep Power: 0
![]() |
Re: retaining values in methods
All right. So it only crashes if you clear while the fields are blank. The way I have it written the input is being tried above the clear actions so obviously if a user presses clear while there are empty text fields this will throw an exception! (you all need an emo face that slaps his head.)
I moved my clear actions above the initiations to keep it from crashing. I think this is proper. public void actionPerformed(ActionEvent e){
try{
String arg = e.getActionCommand();
if(e.getSource() == btnClear || arg == "Clear"){
clear();
return;
}
if(e.getSource() == btnSysClear || arg == "SysClear"){
sysClear();
return;
}
if(e.getSource() == btnExit || arg == "Exit")
System.exit(0);
int index;
int id;
int quant;
String name = txtLname.getText();
quant = comboQty.getSelectedIndex() + 1;
id = Integer.parseInt(txtID.getText());
index = furnCombo.getSelectedIndex();
item = catalog[index];
price = Float.parseFloat(txtPrice.getText());
//***** price chek ******
if(e.getSource() == btnPCheck || arg == "Price Check"){
price = proc(quant, index, false);
}
//***** process **********
if(e.getSource() == btnProc || arg == "Process"){
if(name.compareTo("") == 0 || price < 1) throw new NumberFormatException();
viewport1.setText("");
if(name.compareTo(nameHolder) != 0)
total = 0;
price = proc(quant, index, true);
nameHolder = name;
total += price;
clear();
}
}
catch(NumberFormatException nFx){
JOptionPane.showMessageDialog(null, "You have entered an incorrect value.", "Format Error", JOptionPane.ERROR_MESSAGE);
}
catch(Exception x){
JOptionPane.showMessageDialog(null, "An Error has occured.");
}
finally{
System.out.println("exception cleanup");
}
}//end actionPerformed |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| help on save and save as methods | Yarvin | Python | 2 | Nov 9th, 2006 8:01 PM |
| Arrays as Parameters in Methods | grimpirate | Java | 2 | Jun 22nd, 2006 11:01 PM |
| Returning two values | Navid | C | 19 | Jun 13th, 2005 2:57 AM |
| A standards question, optional inputs into Methods | Arla | C# | 4 | Apr 27th, 2005 10:38 PM |
| Problem Inserting Values into mySQL from PHP | stakeknife | PHP | 1 | Mar 23rd, 2005 8:45 AM |