Help with calling methods of different classes
I have two classes. In class A I read a line of input from the console
myVar= x.readLine();
then I call a method of the same class (A)
methodA(); i get NULLPOINTEREXCEPTION here
in this method I wish to call another method but this time of class B so I create an instance of class B in class A
private B instanceVar;
and then proceed to create the method call to class B
instanceVar.methodB(myVar); i get NULLPOINTEREXCEPTION here
What am I doing wrong?
What am I doing wrong?Not posting a short snippet of java code that demonstrates your problem.
In class A I read a line of input from the console
myVar= x.readLine();
How is that related to the NPE's?
then I call a method of the same class (A)
methodA(); i get NULLPOINTEREXCEPTION hereSomething is probably wrong in methodA(). Impossible to say anything more with the information given.
private B instanceVar;
and then proceed to create the method call to class B
instanceVar.methodB(myVar); i get NULLPOINTEREXCEPTION hereDid you ever assign instanceVar to an actual object with something like instanceVar = new B(); ?
Similar Messages
-
I'm new to Java, trying to pass a required class so I can graduate this semester, and I need help figuring out what is wrong with the code below. My assignment is to create a program to convert celsius to fahrenheit and vice versa using Scanner for input. The program must contain 3 methods - main, convert F to C, method, and convert C to F method. Requirements of the conversion methods are one parameter which is an int representing temp, return an int representing calculated temp after doing appropriate calculation, should not display info to user, and should not take in info from user.
The main method is required to ask the user to input a 1 for converting F to C, 2 for C to F, and 3 to end the program. It must include a while loop that loops until the user enters a 3, ask the user to enter a temp, call the appropriate method to do the conversion, and display the results. I'm having trouble calling the conversion methods and keep getting the following 2 compiler errors:
cannot find symbol
symbol : method farenheitToCelsius(int)
location: class WondaPavoneTempConverter
int celsius = farenheitToCelsius(intTemp);
^
cannot find symbol
symbol : method celsiusToFarenheit(int)
location: class WondaPavoneTempConverter
int farenheit = celsiusToFarenheit(intTemp);
The code is as follows:
public static void main(String[] args) {
// Create a scanner
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter a temperature
System.out.println("Enter the temperature you wish to convert as a whole number: ");
int intTemp = scanner.nextInt();
System.out.println("You entered " + intTemp + " degrees.");
// Prompt the user to enter "1" to convert to Celsius, "2" to convert to
// Farenheit, or "3" to exit the program
System.out.println("Enter 1 to convert to Celsius, 2 to convert to Farenheit, or 3 to exit.");
int intConvert = scanner.nextInt();
// Convert temperature to Celsius or Farenheit
int celsius = farenheitToCelsius(intTemp);
int farenheit = celsiusToFarenheit(intTemp);
while (intConvert >= 0) {
// Convert to Celsius
if (intConvert == 1) {
System.out.println("Celsius is " + celsius + " degrees.");
// Convert to Farenheit
else if (intConvert == 2) {
System.out.println("Farenheit is " + farenheit + " degrees.");
// Exit program
else if (intConvert == 3) {
break;
else {
System.out.println("The number you entered is invalid. Please enter 1, 2, or 3.");
//Method to convert Celsius to Farenheit
public static int celsiusToFahrenheit(int cTemp) {
return (9 / 5) * (cTemp + 32);
//Method to convert Farenheit to Celsius
public static int fahrenheitToCelsius(int fTemp) {
return (5 / 9) * (fTemp - 32);
I readily admit I'm a complete dunce when it comes to programming - digital media is my area of expertise. Can anyone point me in the right direction? This assignment is due very soon. Thanks.1) consider using a boolean variable in the while statement and converting it to true if the input is good.
while (inputNotValid)
}2) put the code to get the input within the while loop. Try your code right now and enter the number 30 when your menu requests for input and you'll see the infinite loop.... and why you need to request input within the loop.
3) Fix your equations. You are gonig to have to do some double calcs, even if you convert it back to int for the method return. Otherwise the results are just plain wrong. As a good test, put in the numbers -40, 0, 32, 100, and 212. Are the results as expected? (-40 is the only temp that is the same for both cent and fahr). I recommend doing double calcs and then casting the result to int in the return. for example:
int a = (int) (20 + 42.0 / 3); // the 42.0 forces the compiler to do double calc.4) One of your equations may still be plain wrong even with this fix. Again, run the test numbers and see.
5) Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag [code] at the top of your block of code and the tag [/code] at the bottom, like so:
[code]
// your code block goes here.
[/code] -
Re: help with calling methods
TL;DR--OK, here are 2 things for you to check
1 - are you making changes to your object in a scope as a passed by value variable?
public void myMethod(MyObject o){
o.my_int = 66;
}when you return from this method, my_int will be the same as it was before you entered.
2 - are you making changes to what you think is your object, but is a local copy?
class MyClass{
String s = "This is a test";
MyClass{
String s = "My inialized String";
}even through you changed s in your constructor (you can say any method here), you defined a local variable called s and actually modified the local variable leaving your class variable s altered.alright guys all yall who posted replies thanks.
i found out what was wrong. my program was working perfectly. I had flaws in basic math equations that made me get 0 for all those things. -
Is it possible to call methods from another class from within an abstract c
Is it possible to call methods from another class from within an abstract class ?
I found an example in teh JDK 131 JFC that may help you. I t is using swing interface and JTable
If you can not use Swing, then you may want to do digging or try out with the idea presented here in example 3
Notice that one should refine the abstract table model and you may want to create a method for something like
public Object getValuesAtRow(int row) { return data[row;}
to give the desired row and leave the method for
getValuesAt alone for getting valued of particaular row and column.
So Once you got the seelcted row index, idxSelctd, from your table
you can get the row or set the row in your table model
public TableExample3() {
JFrame frame = new JFrame("Table");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}});
// Take the dummy data from SwingSet.
final String[] names = {"First Name", "Last Name", "Favorite Color",
"Favorite Number", "Vegetarian"};
final Object[][] data = {
{"Mark", "Andrews", "Red", new Integer(2), new Boolean(true)},
{"Tom", "Ball", "Blue", new Integer(99), new Boolean(false)},
{"Alan", "Chung", "Green", new Integer(838), new Boolean(false)},
{"Jeff", "Dinkins", "Turquois", new Integer(8), new Boolean(true)},
{"Amy", "Fowler", "Yellow", new Integer(3), new Boolean(false)},
{"Brian", "Gerhold", "Green", new Integer(0), new Boolean(false)},
{"James", "Gosling", "Pink", new Integer(21), new Boolean(false)},
{"David", "Karlton", "Red", new Integer(1), new Boolean(false)},
{"Dave", "Kloba", "Yellow", new Integer(14), new Boolean(false)},
{"Peter", "Korn", "Purple", new Integer(12), new Boolean(false)},
{"Phil", "Milne", "Purple", new Integer(3), new Boolean(false)},
{"Dave", "Moore", "Green", new Integer(88), new Boolean(false)},
{"Hans", "Muller", "Maroon", new Integer(5), new Boolean(false)},
{"Rick", "Levenson", "Blue", new Integer(2), new Boolean(false)},
{"Tim", "Prinzing", "Blue", new Integer(22), new Boolean(false)},
{"Chester", "Rose", "Black", new Integer(0), new Boolean(false)},
{"Ray", "Ryan", "Gray", new Integer(77), new Boolean(false)},
{"Georges", "Saab", "Red", new Integer(4), new Boolean(false)},
{"Willie", "Walker", "Phthalo Blue", new Integer(4), new Boolean(false)},
{"Kathy", "Walrath", "Blue", new Integer(8), new Boolean(false)},
{"Arnaud", "Weber", "Green", new Integer(44), new Boolean(false)}
// Create a model of the data.
TableModel dataModel = new AbstractTableModel() {
// These methods always need to be implemented.
public int getColumnCount() { return names.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col) {return data[row][col];}
// The default implementations of these methods in
// AbstractTableModel would work, but we can refine them.
public String getColumnName(int column) {return names[column];}
public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
public boolean isCellEditable(int row, int col) {return (col==4);}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
}; -
Error when calling method INIT in class cl_hrxss_rem for salary statements
after configuring the our hrform to work with the new ess system in ecc 6.0 we configured the hrfor decision tree to $cedt$ and pointed the form variant to the edtin feature.
Now we are getting a class error.
com.sap.pcuigp.xssfpm.java.FPMRuntimeException: Error when calling method INIT of class CL_HRXSS_REM
at com.sap.pcuigp.xssfpm.java.MessageManager.raiseException(MessageManager.java:111)
at com.sap.pcuigp.xssfpm.java.MessageManager.raiseException(MessageManager.java:121)
at com.sap.xss.hr.rep.fcrfw.FcRepFramework.reportBapiRet2Error(FcRepFramework.java:525)
at com.sap.xss.hr.rep.fcrfw.FcRepFramework.callRfcExecAction(FcRepFramework.java:374)
at com.sap.xss.hr.rep.fcrfw.FcRepFramework.initModel(FcRepFramework.java:292)
at com.sap.xss.hr.rep.fcrfw.wdp.InternalFcRepFramework.initModel(InternalFcRepFramework.java:256)
at com.sap.xss.hr.rep.fcrfw.FcRepFrameworkInterface.initModel(FcRepFrameworkInterface.java:136)
at com.sap.xss.hr.rep.fcrfw.wdp.InternalFcRepFrameworkInterface.initModel(InternalFcRepFrameworkInterface.java:198)
at com.sap.xss.hr.rep.fcrfw.wdp.InternalFcRepFrameworkInterface$External.initModel(InternalFcRepFrameworkInterface.java:258)
at com.sap.xss.hr.rem2.selection.VcRem2Selection.onInit(VcRem2Selection.java:245)
at com.sap.xss.hr.rem2.selection.wdp.InternalVcRem2Selection.onInit(InternalVcRem2Selection.java:249)
at com.sap.xss.hr.rem2.selection.VcRem2SelectionInterface.onInit(VcRem2SelectionInterface.java:161)
at com.sap.xss.hr.rem2.selection.wdp.InternalVcRem2SelectionInterface.onInit(InternalVcRem2SelectionInterface.java:144)
at com.sap.xss.hr.rem2.selection.wdp.InternalVcRem2SelectionInterface$External.onInit(InternalVcRem2SelectionInterface.java:220)
at com.sap.pcuigp.xssfpm.wd.FPMComponent.doProcessEvent(FPMComponent.java:564)
at com.sap.pcuigp.xssfpm.wd.FPMComponent.doEventLoop(FPMComponent.java:438)
at com.sap.pcuigp.xssfpm.wd.FPMComponent.wdDoInit(FPMComponent.java:196)
at com.sap.pcuigp.xssfpm.wd.wdp.InternalFPMComponent.wdDoInit(InternalFPMComponent.java:110)
at com.sap.tc.webdynpro.progmodel.generation.DelegatingComponent.doInit(DelegatingComponent.java:108)
at com.sap.tc.webdynpro.progmodel.controller.Controller.initController(Controller.java:215)
at com.sap.tc.webdynpro.progmodel.controller.Controller.init(Controller.java:200)
at com.sap.tc.webdynpro.clientserver.cal.ClientComponent.init(ClientComponent.java:430)
at com.sap.tc.webdynpro.clientserver.cal.ClientApplication.init(ClientApplication.java:362)
at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.initApplication(ApplicationSession.java:748)
at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.doProcessing(ApplicationSession.java:283)
at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessingPortal(ClientSession.java:733)
at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessing(ClientSession.java:668)
at com.sap.tc.webdynpro.clientserver.session.ClientSession.doProcessing(ClientSession.java:250)
at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:149)
at com.sap.tc.webdynpro.clientserver.session.core.ApplicationHandle.doProcessing(ApplicationHandle.java:73)
at com.sap.tc.webdynpro.portal.pb.impl.AbstractApplicationProxy.sendDataAndProcessActionInternal(AbstractApplicationProxy.java:860)
at com.sap.tc.webdynpro.portal.pb.impl.AbstractApplicationProxy.create(AbstractApplicationProxy.java:220)
at com.sap.portal.pb.PageBuilder.updateApplications(PageBuilder.java:1246)
at com.sap.portal.pb.PageBuilder.createPage(PageBuilder.java:354)
at com.sap.portal.pb.PageBuilder.init(PageBuilder.java:547)
at com.sap.portal.pb.PageBuilder.wdDoRefresh(PageBuilder.java:591)
at com.sap.portal.pb.PageBuilder$1.doPhase(PageBuilder.java:822)
at com.sap.tc.webdynpro.clientserver.window.WindowPhaseModel.processPhaseListener(WindowPhaseModel.java:755)
at com.sap.tc.webdynpro.clientserver.window.WindowPhaseModel.doPortalDispatch(WindowPhaseModel.java:717)
at com.sap.tc.webdynpro.clientserver.window.WindowPhaseModel.processRequest(WindowPhaseModel.java:136)
at com.sap.tc.webdynpro.clientserver.window.WebDynproWindow.processRequest(WebDynproWindow.java:335)
at com.sap.tc.webdynpro.clientserver.cal.AbstractClient.executeTasks(AbstractClient.java:143)
at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.doProcessing(ApplicationSession.java:313)
at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessing(ClientSession.java:684)
at com.sap.tc.webdynpro.clientserver.session.ClientSession.doProcessing(ClientSession.java:250)
at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:149)
at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doPost(DispatcherServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:401)
at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:387)
at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:365)
at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:944)
at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:266)
at com.sap.engine.services.httpserver.server.Client.handle(Client.java:95)
at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:175)
at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
at java.security.AccessController.doPrivileged(Native Method)
at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)
ThanksHi,
Maintain the EDTIN feature
&CEDT$
And UR problem solve -
Hi, I am new to java and need help with sound methods.
q: create a new method that will halve the volume of the positive values and double the volume of the negative values.
Message was edited by:
Apaula30duplicate message #2
-
Calling a method from different class
Hey peeps,
say i have a method in another class and i wish to call it, what would the code be for that?
say for example the method was called createNewShoeBox and i was in another class?
hope that makes sencejermaindefoe wrote:
lol! id love to have one, and in which case would love to have the money for one as id definatley take it up,In the following part, you're saying you're a student. So there are peers you can ask, if not your professor. There are certainly also some who actualy know some programming and would teach you if you just asked them.
im a first year student bear in mind though lol!!! and ma struggling, I see that, and the way you handle your problems, that won't change for the next few years.
i may not be as good at java as you, but i can do other things better than you can, and thats life, we all have to start somewhereWhat you also can't do as well as I do is "realizing that using an internet forum is one of the worse ways to have people helping you to learn programming". You're lacking a lot of understanding for concepts where the label "basic" is almost exaggerating. I'm sure you can get that understanding, but being spoon-fed through a forum with no visible effort to figure things out is not the way to do it. -
Updating JPanel with buttons from a different class
I have a JPanel in a class that has a gridlayout with buttons in it for a game board. And my problem is that when I want to update a button using setIcon() the button doesn't change in the GUI because the buttons are in a different class. The JPanel is in a Client class and the buttons are in a GamePlugin class. I've tried a bunch of different things but none of them worked or it was way too slow. I'm sure theres an easy way to do it that I'm not seeing. Any suggestions? Heres part of my code for updating the GUI.
private JPanel boardPanel = new JPanel();
Container cP = getContentPane();
cP.add(boardPanel, BorderLayout.WEST);
boardPanel.setPreferredSize(new Dimension(400, 400));
boardPanel.setLayout(new GridLayout(8, 8));
cP.add(optionsPanel, BorderLayout.CENTER);
* Gets the board panel from the selected plugin.
public void drawGameBoard(GamePlugin plugin) {
board = (OthelloPlugin)plugin;
boardPanel = board.getBoardPanel();
for (int i = 0; i < GamePlugin.BOARD_SIZE; i++)
for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
board.boardButtons[i][j].setActionCommand("" + i + "" + j);
board.boardButtons[i][j].addActionListener(this);
* This method takes a GameBoard and uses it to update this class' data
* and GUI representation of the board.
public void updateBoard(GamePlugin updatedBoard) {
board = (OthelloPlugin)updatedBoard;
for (int i = 0; i < GamePlugin.BOARD_SIZE; i++) {
for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
int cell = board.getCell(i,j);
if (cell == OthelloPlugin.PLAYER1){
board.boardButtons[i][j].setIcon(black);
else if (cell == OthelloPlugin.PLAYER2)
board.boardButtons[i][j].setIcon(white);
else
board.boardButtons[i][j].setText("");
}txp200:
I agree that a call to validate() , possibly repaint(), should fix your problem. In the class with the panel that the buttons are on, i would create a static repaint method that call panel.repaint(). You can then call that method in your other class. Just make sure u only use methods to change the properties of the button, never make a make a new one, as then you will lose the association with the panel. Hope this helps.
-- Brady E -
JFrame not showing components when called method in other class
Hi everyone,
I am new to SWING,and have this little problem.
i have created a JFrame which has a button and its calling a method in another class.the result takes much more time(around 3mins) as the call involved with FTP.
My problem is , i click the button(other componetns also there),and waiting for the result.all the time my Frame doesnt show any of the components,it looks as if the components are added to it.but when the call returns.everything is OK.
Can any1 help me?
Thanx in advance
ethirajanhttp://java.sun.com/docs/books/tutorial/essential/threads/
http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html -
Issue with close() method of BufferedReader class and FileInputStream class
I have written the following code to a text file, called hello,txt from Windows. Everything works fine but I am trying to figure out whether calling of close() method of aforemetioned class is appropriate or necessary thing to do.
Here are the questions:
1. Is it necessary to call close method in this senario? And why? [it seems to me that everything gets cleaned up automatically anyways at the end of each call to the method when called from main()]
2. If the answer for No.1 is yes, then in which order each close method should be called? Or, does the order of calling close method matter anyways?
3. Is the reason for why in No.1 is that because calling close method on each object is a necessary step to do when dealing with mutli-thread?
Thanks for your help in advance!
* Below is an example to clarify my questions
void readWinFile() {
File objFile = new File("hello.txt");
FileInputStream fileStream = null;
BufferedReader bfReader = null;
try {
fileStream = new FileInputStream(objFile);
bfReader = new BufferedReader(
new InputStreamReader(fileStream, "MS932"));
int tmp;
while ((tmp = bfReader.read()) != -1) {
System.out.print((char)tmpLine);
} catch (FileNotFoundException e) {
System.err.printf("File: %s Not Found @ DIR = %s",
objFile.getName(), objFile.getParent());
} catch (UnsupportedEncodingException e) {
System.err.printf("Internal failure: %s", e);
} catch (IOException e) {
System.err.printf("File: %s close failure", objFile.getName());
* } finally {*
* if (bfReader != null) {*
* try {*
* bfReader.close();*
* } catch (IOException e) {*
* e.printStackTrace();*
* if (fileStream != null) {*
* try {*
* fileStream.close();*
* } catch (IOException e) {*
* e.printStackTrace();*
}Edited by: Jay-K on Feb 14, 2010 8:50 PM
Edited by: Jay-K on Feb 14, 2010 8:52 PMHello CeciNEstPasUnProgrammeur,
Thank you for taking your time and doing all these write-up for me.
CeciNEstPasUnProgrammeur wrote:
Pretty much every native resource, most notably DB connections because those even remain open after the client process terminates. But ports or file handlers are similar; note that a JVM does not necessarily terminate just because you close your program in "extreme cases" (shared use of JVM). In an app server this is certainly never the way. And even if it does, as long as your app is running, the stuff is certainly never released.What you meant is that if my app runs on an app server, which shared the use of JVM with multiple apps, without properly closing ports or file handlers could cause JVM to keep retaining the native resource allocated for my app. In case of that, the resource leaks would occur.
On the other hand, if my app runs on an app server, which do not share the use of JVM, the leaks would be less likely to happen even if the ports or file handlers are not manually closed. (It could be a very poor design but technically I could reply on their finalizers to clean up the mess)
>
Another misconception seems to be that objects are automatically GCed the moment they run out of scope. This is not true.Is there any documentation somewhere that you could refer me to? I would like to figure out why objects are not auto-GCed when they run out of their scope.
>
And lastly, objects should not rely on their finalizers to release native resources, and should rather provide close/release methods. This is a common paradigm, and that's also why releasing the file handle won't work by simply letting the reader instance run out of scope. Nobody notifies the underlying OS.I see, so the JVM here interacts with the underlying OS to acquire sufficient native resource for its apps to run. Without explicit closing, which would make JVM not to notify underlying OS to release acquired resource. Am I on the ball here?
Thanks,
Jay -
Calling method from another class
Got the below code for the Bank class with a log in system, Want i need is a While loop for
"While ValidUser = True, Do method in Accounts class."
package bank;
import javax.swing.*;
import java.lang.*;
public class Bank {
/*User Arrays */
public String Customer[]= new String[4];
public String Pin[] = new String[4];
/* User Tryed details */
String User;
String PinAuth;
Boolean ValidUser;
public Bank ()
/*Customers */
Customer[0]="John";
Customer[1]="Alan";
Customer[2]="Lisa";
Customer[3]="Liam";
Pin[0]="1234";
Pin[1]="1982";
Pin[2]="4321";
Pin[3]="5678";
public Bank(String CustAtt, String PinAtt)
User = CustAtt;
PinAuth = PinAtt;
public String getUser()
return User;
public String getPin()
return PinAuth;
public void setUser(String CustAtt)
User = CustAtt;
public void setPin(String PinAtt)
PinAuth = PinAtt;
public static void main (String args[] ){
System.out.println("Welcome to The Bank of Scotland");
String User;
String PinAtt;
boolean ValidUser;
/* Get User Details */
User =
JOptionPane.showInputDialog("Please Enter Your Name");
/* Get User pin */
PinAtt =
JOptionPane.showInputDialog("Enter your Pin");
/* Print USer Details */
System.out.println(User);
System.out.println(PinAtt);
/* Authorise Customer */
Bank newBank = new Bank();
for(int i=0; i<4;i++)
if(User.equals(newBank.Customer) && PinAtt.equals(newBank.Pin[i]))
ValidUser=true;
else
ValidUser=false;
if(ValidUser=true)
System.out.println("Auth");
else if(ValidUser=false)
System.out.println("Log in details are in correct");
while(ValidUser=true)
Account Class, in this class i need options for selecting withdraw deposit and close account, not sure if i could do this in the Current account class though.
Any advice will be great package bank;
import javax.swing.*;
import java.lang.*;
public class Account {
private String AccountNo;
private int Balance;
private int Deposit;
String AccountUsed;
public Account () {
public String getAccountNo ()
return AccountNo;
public void setAccountNo (int val) {
AccountUsed = AccountNo;
public int getBalance () {
return Balance;
public void setBalance (int val) {
this.Balance = val;
public int getDeposit ()
return Deposit;
public void setDeposit (int val)
this.Deposit = val;
this.Balance=this.Balance+this.Deposit;
public void setWithdrawl (int val)
this.Balance=this.Balance-val;
public static void account (String args[] ){
String Deposit = new String();
String Withdraw = new String() ;
System.out.println("Deposit - Withdraw");
Account newAccount = new Account();
Deposit =
JOptionPane.showInputDialog("Enter the ammount you wish to deposit");
Withdraw =
JOptionPane.showInputDialog("Enter the amount you wish to Withdraw");
System.out.println(Deposit);
System.out.println(Withdraw);
Account custAccount =new Account();
custAccount.setDeposit(Integer.parseInt(Deposit));
custAccount.setWithdrawl(Integer.parseInt(Withdraw));
System.out.println(custAccount.getBalance());Maxideon wrote:
All of these are valid,
while(validUser == true) {
while(validUser) {
//I prefer this one
if(validUser == true) {
if(validUser) {
//I prefer this one
} What you have,
if(validUser = true) {
if(validUser = false) {
}is different. I have two equal signs, while you have one. What do you think one equal sign does?
P.S. All your variable names are screwed up. They should begin with a lower case letter.
Edit
Some other anomalies: you declared ValidUser as a Boolean and you imported java.lang. .... Why?
Edit
Another weird thing.
String Deposit = new String();
String Withdraw = new String();?I Am fairly new to java, I have things "working" to an extent, and i am aware of the naming conventions over the variable names, -
Calling method from another class problem
hi,
i am having problem with my code. When i call the method from the other class, it does not function correctly?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Dice extends JComponent
private static final int SPOT_DIAM = 9;
private int faceValue;
public Dice()
setPreferredSize(new Dimension(60,60));
roll();
public int roll()
int val = (int)(6*Math.random() + 1);
setValue(val);
return val;
public int getValue()
return faceValue;
public void setValue(int spots)
faceValue = spots;
repaint();
@Override public void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, w, h);
g2.setColor(Color.BLACK);
g2.drawRect(0, 0, w-1, h-1);
switch (faceValue)
case 1:
drawSpot(g2, w/2, h/2);
break;
case 3:
drawSpot(g2, w/2, h/2);
case 2:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
break;
case 5:
drawSpot(g2, w/2, h/2);
case 4:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
break;
case 6:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
drawSpot(g2, w/4, h/2);
drawSpot(g2, 3*w/4, h/2);
break;
private void drawSpot(Graphics2D g2, int x, int y)
g2.fillOval(x-SPOT_DIAM/2, y-SPOT_DIAM/2, SPOT_DIAM, SPOT_DIAM);
}in another class A (the main class where i run everything) i created a new instance of dice and added it onto a JPanel.Also a JButton is created called roll, which i added a actionListener.........rollButton.addActionListener(B); (B is instance of class B)
In Class B in implements actionlistener and when the roll button is clicked it should call "roll()" from Dice class
Dice d = new Dice();
d.roll();
it works but it does not repaint the graphics for the dice? the roll method will get a random number but then it will call the method to repaint()???
Edited by: AceOfSpades on Mar 5, 2008 2:41 PM
Edited by: AceOfSpades on Mar 5, 2008 2:42 PMOne way:
class Flintstone
private String name;
public Flintstone(String name)
this.name = name;
public String toString()
return name;
public static void useFlintstoneWithReference(Flintstone fu2)
System.out.println(fu2);
public static void useFlintstoneWithOutReference()
Flintstone barney = new Flintstone("Barney");
System.out.println(barney);
public static void main(String[] args)
Flintstone fred = new Flintstone("Fred");
useFlintstoneWithReference(fred); // fred's the reference I"m passing to the method
useFlintstoneWithOutReference();
{code}
can also be done with action listener
{code} private class MyActionListener implements ActionListener
private Flintstone flintstone;
public MyActionListener(Flintstone flintstone)
this.flintstone = flintstone;
public void actionPerformed(ActionEvent arg0)
//do whatever using flinstone
System.out.println(flintstone);
}{code}
Edited by: Encephalopathic on Mar 5, 2008 3:06 PM -
Issue with CHECK_CHANGED_DATA method of CL_GUI_ALV_GRID class
HI,
I want to check whether my grid has any changes or not, for that i am using the CHECK_CHANGED_DATA method of CL_GUI_ALV_GRID class,
What i am doing is.... I am doing some changes in my grid data and clicking on SAVE . This time CHECK_CHANGED_DATA is saying the grid have changes ,and i am displaying a pop up whether to save the changes or not. And i am saving changes.
Till now Fine.
If i click on SAVE again CHECK_CHANGED_DATA is showing again the Grid has changes.
So how can i solve this problem.
Thanks in advance.Hello Narendra
If you do not need to do any validations of the changed ALV list data then you can use a very simple approach which does not even require an event handler for event DATA_CHANGED.
The crucial part of the coding is shown below, followed by the entire sample report ZUS_SDN_ALV_EDITABLE_1A. Basically, the ALV list is stored as a "PBO" image of the data (GT_OUTTAB_PBO). And only if the user changed the data (i.e. GT_OUTTAB_PBO <> GT_OUTTAB) the save option including the popup is executed.
*& Module USER_COMMAND_0100 INPUT
* text
MODULE user_command_0100 INPUT.
" NOTE: retrieve changed data from frontend (grid control) into
" the backend (itab in ABAP)
go_grid->check_changed_data( ).
CASE gd_okcode.
WHEN 'BACK' OR
'EXIT' OR
'CANC'.
SET SCREEN 0. LEAVE SCREEN.
WHEN 'SAVE'.
IF ( gt_outtab = gt_outtab_pbo ).
MESSAGE 'No data changed' TYPE 'S'.
ELSE.
CLEAR: gd_answer.
CALL FUNCTION 'POPUP_TO_CONFIRM'
EXPORTING
* TITLEBAR = ' '
* DIAGNOSE_OBJECT = ' '
text_question = 'Save data?'
IMPORTING
answer = gd_answer
* TABLES
* PARAMETER =
EXCEPTIONS
text_not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
IF ( gd_answer = '1' ). " yes
MESSAGE 'Data successfully saved' TYPE 'S'.
gt_outtab_pbo = gt_outtab. " update PBO data !!!
ELSE.
MESSAGE 'Action cancelled by user' TYPE 'S'.
ENDIF.
ENDIF.
WHEN OTHERS.
ENDCASE.
CLEAR: gd_okcode.
ENDMODULE. " USER_COMMAND_0100 INPUT
*& Report ZUS_SDN_ALV_EDITABLE
* Flow logic of screen '100' (no elements, ok-code => gd_okcode ):
**PROCESS BEFORE OUTPUT.
** MODULE STATUS_0100.
**PROCESS AFTER INPUT.
** MODULE USER_COMMAND_0100.
REPORT zus_sdn_alv_editable_1a.
TYPE-POOLS: abap.
CONSTANTS:
gc_tabname TYPE tabname VALUE 'KNB1'.
TYPES: BEGIN OF ty_s_outtab.
INCLUDE TYPE knb1.
TYPES: END OF ty_s_outtab.
TYPES: ty_t_outtab TYPE STANDARD TABLE OF ty_s_outtab
WITH DEFAULT KEY.
DATA:
gd_okcode TYPE ui_func,
gd_repid TYPE syst-repid,
gt_fcat TYPE lvc_t_fcat,
gs_layout TYPE lvc_s_layo,
gs_variant TYPE disvariant,
go_docking TYPE REF TO cl_gui_docking_container,
go_grid TYPE REF TO cl_gui_alv_grid.
DATA:
gs_outtab TYPE ty_s_outtab,
gt_outtab TYPE ty_t_outtab,
gt_outtab_pbo TYPE ty_t_outtab.
DATA:
gd_answer TYPE c.
START-OF-SELECTION.
SELECT * FROM (gc_tabname) INTO TABLE gt_outtab UP TO 99 ROWS.
gt_outtab_pbo = gt_outtab. " set PBO data
PERFORM init_controls.
* ok-code field = GD_OKCODE
CALL SCREEN '0100'.
END-OF-SELECTION.
*& Form INIT_CONTROLS
* text
* --> p1 text
* <-- p2 text
FORM init_controls .
* Create docking container
CREATE OBJECT go_docking
EXPORTING
parent = cl_gui_container=>screen0
ratio = 90
EXCEPTIONS
OTHERS = 6.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
* Create ALV grid
CREATE OBJECT go_grid
EXPORTING
i_parent = go_docking
EXCEPTIONS
OTHERS = 5.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
" NOTE: not required
* set handler:
* lcl_eventhandler=>handle_data_changed for go_grid.
* Build fieldcatalog and set hotspot for field KUNNR
PERFORM build_fieldcatalog.
PERFORM set_layout_and_variant.
* Display data
CALL METHOD go_grid->set_table_for_first_display
EXPORTING
is_layout = gs_layout
is_variant = gs_variant
i_save = 'A'
CHANGING
it_outtab = gt_outtab
it_fieldcatalog = gt_fcat
EXCEPTIONS
OTHERS = 4.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
* NOTE:
* Documenation of I_SAVE ("An Easy Reference for ALV Grid Control")
*I_SAVE
*Determines the options available to the user for saving a layout:
*? 'X': global saving only
*? 'U': user-specific saving only
*? 'A': corresponds to 'X' and 'U'
*? SPACE: no saving
* Link the docking container to the target dynpro
gd_repid = syst-repid.
CALL METHOD go_docking->link
EXPORTING
repid = gd_repid
dynnr = '0100'
* CONTAINER =
EXCEPTIONS
OTHERS = 4.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
ENDFORM. " INIT_CONTROLS
*& Module STATUS_0100 OUTPUT
* text
MODULE status_0100 OUTPUT.
SET PF-STATUS 'STATUS_0100'.
* SET TITLEBAR 'xxx'.
ENDMODULE. " STATUS_0100 OUTPUT
*& Module USER_COMMAND_0100 INPUT
* text
MODULE user_command_0100 INPUT.
" NOTE: retrieve changed data from frontend (grid control) into
" the backend (itab in ABAP)
go_grid->check_changed_data( ).
CASE gd_okcode.
WHEN 'BACK' OR
'EXIT' OR
'CANC'.
SET SCREEN 0. LEAVE SCREEN.
WHEN 'SAVE'.
IF ( gt_outtab = gt_outtab_pbo ).
MESSAGE 'No data changed' TYPE 'S'.
ELSE.
CLEAR: gd_answer.
CALL FUNCTION 'POPUP_TO_CONFIRM'
EXPORTING
* TITLEBAR = ' '
* DIAGNOSE_OBJECT = ' '
text_question = 'Save data?'
* TEXT_BUTTON_1 = 'Ja'(001)
* ICON_BUTTON_1 = ' '
* TEXT_BUTTON_2 = 'Nein'(002)
* ICON_BUTTON_2 = ' '
* DEFAULT_BUTTON = '1'
* DISPLAY_CANCEL_BUTTON = 'X'
* USERDEFINED_F1_HELP = ' '
* START_COLUMN = 25
* START_ROW = 6
* POPUP_TYPE =
* IV_QUICKINFO_BUTTON_1 = ' '
* IV_QUICKINFO_BUTTON_2 = ' '
IMPORTING
answer = gd_answer
* TABLES
* PARAMETER =
EXCEPTIONS
text_not_found = 1
OTHERS = 2.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
* Triggers PAI of the dynpro with the specified ok-code
IF ( gd_answer = '1' ). " yes
MESSAGE 'Data successfully saved' TYPE 'S'.
gt_outtab_pbo = gt_outtab. " update PBO data !!!
ELSE.
MESSAGE 'Action cancelled by user' TYPE 'S'.
ENDIF.
ENDIF.
WHEN OTHERS.
ENDCASE.
CLEAR: gd_okcode.
ENDMODULE. " USER_COMMAND_0100 INPUT
*& Form BUILD_FIELDCATALOG
* text
* --> p1 text
* <-- p2 text
FORM build_fieldcatalog .
* define local data
DATA:
ls_fcat TYPE lvc_s_fcat.
CALL FUNCTION 'LVC_FIELDCATALOG_MERGE'
EXPORTING
* I_BUFFER_ACTIVE =
i_structure_name = gc_tabname
* I_CLIENT_NEVER_DISPLAY = 'X'
* I_BYPASSING_BUFFER =
* I_INTERNAL_TABNAME =
CHANGING
ct_fieldcat = gt_fcat
EXCEPTIONS
inconsistent_interface = 1
program_error = 2
OTHERS = 3.
IF sy-subrc <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
ls_fcat-edit = abap_true.
MODIFY gt_fcat FROM ls_fcat
TRANSPORTING edit
WHERE ( key NE abap_true ).
ENDFORM. " BUILD_FIELDCATALOG
*& Form SET_LAYOUT_AND_VARIANT
* text
* --> p1 text
* <-- p2 text
FORM set_layout_and_variant .
CLEAR: gs_layout,
gs_variant.
gs_layout-cwidth_opt = abap_true.
gs_layout-zebra = abap_true.
gs_variant-report = syst-repid.
gs_variant-handle = 'GRID'.
ENDFORM. " SET_LAYOUT_AND_VARIANT
Regards
Uwe -
Need help in compare method of Comparator class
I am writing a program that will display elements of a TreeMap in an order in which I want. By default the order is ascending. To change the order I need to override the compare method of the Comparator class.
I've done this in my code below.
I want to display keys with lower-case 1st and then those with upper-case.
Please help.
import java.util.*;
public class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
String s1 = o1.toString();
String s2 = o2.toString();
return s1.compareTo(s2);
public static void main(String[] args) {
Map names = new TreeMap(new MyComparator());
names.put("a", new Integer(1435));
names.put("b", new Integer(1110));
names.put("A", new Integer(1425));
names.put("B", new Integer(987));
names.put("C", new Integer(1323));
Set namesSet = names.keySet();
Iterator iter = namesSet.iterator();
while(iter.hasNext()) {
String who = (String)iter.next();
System.out.println(who + " => " + names.get(who));
}public int compare(Object o1, Object o2) {
String s1 = o1.toString();
String s2 = o2.toString();
String ss1 = beginsWithLowerLetter(s1)? s1.toUpperCase() : s1.toLowerCase();
String ss2 = beginsWithLowerLetter(s2)? s2.toUpperCase() : s2.toLowerCase();
return ss1.compareTo(ss2);
} -
Call method from another class instance
Forgive me if I don't make sense, I'm relatively new to Java and still not up on all the lingo.
So here's what I want to do... This is probably easier explained with code:
ParentClass.java
public class ParentClass {
public static void main(String[] args)
ChildClass1 child1 = new ChildClass1();
ChildClass2 child2 = new ChildClass2();
System.out.println("ParentClass");
System.out.println(child1.getText());
System.out.println(child2.getText());
ChildClass1.javapublic class ChildClass1 {
private String text = "ChildClass1";
public ChildClass1()
System.out.println("ChildClass1 Constructor");
public String getText()
{ return text; }
}ChildClass2.java is identical to ChildClass1, except the 1's replaced with 2's etc.
I need to be able to call getText() in ChildClass1 from ChildClass2, and eventually methods in the ParentClass class.
As I understand, if I make the ChildClass's extend the ParentClass, every new instance of the ChildClass will create a new instance of the ParentClass. What I need though, is one instance of ParentClass with it's eventual variables etc. set, and then have the two classes defined within, able to talk to each other and the methods in the ParentClass.
How does one go about doing this? Does that even make sense?
Thanks, SavageYou may need to read thru the information provided on this page to understand how to create objects: http://java.sun.com/docs/books/tutorial/java/data/objectcreation.html
I'd also suggest you read the tutorial available at: http://java.sun.com/docs/books/tutorial/java/index.html
Regarding how you call a method belonging to another class you could do it in the foll. ways depending on whether the method is static or not - a static method may be called using the class name followed by a dot and the static method name while a non-static method would require you to create an instance of the class and then use that instance name followed by a dot and the method name. All said and done i'd still suggest you read thru the complete Java programming tutorial to get a good grounding on all these concepts and fundamentals of the language if you are looking to master the technology.
Thanks
John Morrison
Maybe you are looking for
-
Hello everyone, I have a BPM that executes an ABAP Proxy, my problem is that I need to send in the ABAP Proxy strcuture the Unique Message Id that the BPM has in XI, I don't know if I can obtain this field in Message Mapping and map it to the ABAP Pr
-
Disable copy and paste function in jtextfield
I wish to disable the copy and paste function (CTRL+C and CTRL+V) of the data in the jtextfield... anybody can help?
-
Where is the java control panel in OS 10.10
There have been a rash of pop-ups alerting me to an important Java Update download. Each time its download appears to be complete in the progress bar it never actually finishes and ultimately fails. Are there any known phishing scams happening in
-
Calendar Syncronization between 6700 and Lotus Not...
Hello, every appointment created on my mobile 6700 appears as "public" on the Lotus Notes server after syncronization. Questions: - is there a way to create an appointment on the mobile as "private"? - is there a way to set a category on a newly crea
-
A want a client progrma to connect to the server by pressing a button. But the method to run a client is by typing: "java HelloClient" before run the program. How can I call the client connection when I already run the program(an applet)? Thanks~~