Problems searching empty user database with ObjectDB - java

I am creating a java application which uses ObjectDB to create and maintain a set of databases. I'm currently trying to implement a DB to store user objects consisting of username and password strings. On a JFrame/swing class I have a button for creating new users, when this button is clicked, I want the following to happen:
Create (or connect to) database
Search the database to see if a user object exists with supplied username
if user already exists show a dialog message, otherwise create the user
However, when this button is clicked I get a 'User not found' error on the line which uses the results from the query object. I'm pretty sure it's because I have an empty database, however I want the code to work for the first time the program is ran, so it needs to handle an empty database. I've tried changing the code to create a new user before the query is first run, then the code works how I want it to each time the button is clicked, and it can detect whether or not a new user needs to be created.
I tried to create a 'default' or 'admin' type user so the search would work, however this means a repeat 'default' user will be created every time the program is ran, which is obviously an unwanted feature, and I can't do a query to check if the database is empty (so I could only create the default user on the first run of the program), because that is the problem I was having in the first place!
So, to anyone experienced with ObjectDB, is there a way I can handle the case where an empty database is searched?
Here's the relevant parts of my code:
public class FrameLogIn extends JFrame {
private JPanel contentPane;
private String username;
char[] password;
private static EntityManager em;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameLogIn frame = new FrameLogIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public FrameLogIn() {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("user.odb");
em = emf.createEntityManager();
final JTextField txtUsername = new JTextField();
txtUsername.setFont(new Font("Segoe UI Light", Font.PLAIN, 30));
txtUsername.setHorizontalAlignment(SwingConstants.CENTER);
txtUsername.setToolTipText("username");
txtUsername.setText("");
txtUsername.setBounds(220, 30, 177, 52);
contentPane.add(txtUsername);
txtUsername.setColumns(10);
final JPasswordField passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.PLAIN, 30));
passwordField.setHorizontalAlignment(SwingConstants.CENTER);
passwordField.setBounds(220, 93, 177, 52);
contentPane.add(passwordField);
JButton btnNewUser = new JButton("New user");
btnNewUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
username = txtUsername.getText();
password = passwordField.getPassword();
System.out.println(username);
TypedQuery<Long> q = em.createQuery(
"SELECT COUNT(u) FROM User u "
+ "WHERE u.name = '" + username + "'", Long.class);
if (q.getSingleResult()>0) {
JOptionPane.showMessageDialog(contentPane.getParent(), "A user with this name already exists.");
} else {
em.getTransaction().begin();
User newUser = new User(username, password.toString());
em.persist(newUser);
em.getTransaction().commit();
JOptionPane.showMessageDialog(contentPane.getParent(), "User created.");
}
}
});
btnNewUser.setFont(new Font("Segoe WP Semibold", Font.PLAIN, 25));
btnNewUser.setBackground(Color.WHITE);
btnNewUser.setBounds(71, 175, 149, 63);
contentPane.add(btnNewUser);
}
}
and the error:
Exception in thread "AWT-EventQueue-0" [ObjectDB 2.5.3_03] SELECT COUNT(u) FROM ==> User <== u WHERE u.name = ''
javax.persistence.PersistenceException
Type User is not found (error 301)
(position 21) at com.objectdb.jpa.JpaQuery.getSingleResult(JpaQuery.java:723)
at sg.FrameLogIn$2.actionPerformed(FrameLogIn.java:113)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: com.objectdb.o.TEX: Type User is not found
at com.objectdb.o.MSG.e(MSG.java:107)
at com.objectdb.o.TRS.g(TRS.java:212)
at com.objectdb.o.SYR.q(SYR.java:259)
at com.objectdb.o.SYR.n(SYR.java:188)
at com.objectdb.o.QRC.<init>(QRC.java:152)
at com.objectdb.o.QRM.U6(QRM.java:250)
at com.objectdb.o.MST.U6(MST.java:933)
at com.objectdb.o.WRA.U6(WRA.java:293)
at com.objectdb.o.WSM.U6(WSM.java:114)
at com.objectdb.o.QRR.g(QRR.java:245)
at com.objectdb.o.QRR.f(QRR.java:154)
at com.objectdb.jpa.JpaQuery.getSingleResult(JpaQuery.java:716)
... 37 more
Thanks, also for the record i will not be storing plaintext passwords, I'm just trying to get a basic DB working before I start implementing hashed passwords.

This could happen if the entity class is not in the database yet (no instances of that class have been persisted yet), and a persistence unit is not defined.
If this seems to be the cause, either define a persistence unit or introduce the class to ObjectDB before the query, for example by:
em.getMetamodel().entity(User.class);

Related

How can I parse a value from a JTextField into an Integer and perform some math operations on it?

So, I've been trying to make a Celsius converter in Java using swing and got stuck on getting the input from the JTextField and parsing it into an Integer so i can perform an equation on it. If I leave it as a String I am unable to do any math operations.
I've added a private string called cValue in which I store the value of text field in, and then I have some code in the ActionListener that parses that string into an Integer.
When I run the program it opens up the window without any problems. I can type in anything in the text field, but as soon as I press the button the program exits out and I'm shown an error which I can't understand. If I move the code out of the action listener and run the program, it gives me an error.
Now, I'm pretty new to Java and am not that familiar with it yet. I wrote this using eclipse and made the UI with WindowBuilder. I've tried many things and nothing has worked so far. I appreciate any form of feedback I can get.
This is the code:
private String cValue;
private String result = "0";
private JPanel contentPane;
private JTextField celsiusField;
private JButton convertButton;
/**
* Create the frame.
*/
public CelsiusConverter() {
setDefaultCloseOperation(CelsiusConverter.EXIT_ON_CLOSE);
setBounds(100, 100, 194, 134);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblCelsius = new JLabel("Celsius");
lblCelsius.setBounds(10, 11, 61, 14);
contentPane.add(lblCelsius);
celsiusField = new JTextField();
celsiusField.setBounds(81, 8, 86, 20);
contentPane.add(celsiusField);
celsiusField.setColumns(10);
JLabel lblFahrenheit = new JLabel("Fahrenheit:");
lblFahrenheit.setBounds(10, 73, 70, 14);
contentPane.add(lblFahrenheit);
JLabel lblResult = new JLabel();
lblResult.setText(String.valueOf(result));
lblResult.setBounds(81, 73, 87, 14);
contentPane.add(lblResult);
cValue = celsiusField.getText();
convertButton = new JButton("Convert");
convertButton.setBounds(10, 39, 157, 23);
contentPane.add(convertButton);
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int parsed = Integer.parseInt(cValue);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CelsiusConverter frame = new CelsiusConverter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And this is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at learningWindowBuilder.CelsiusConverter$1.actionPerformed(CelsiusConverter.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
cValue = celsiusField.getText();
You can't invoke that statement yet because the GUI isn't even visible and the user hasn't had a chance to enter data into the text field.
You need to get the text from the text field in your ActionListener
String cValue = celsiusField.getText();
int parsed = Integer.parseInt(cValue);

Creating GUI for composing email message

I am trying to create an application for composing an email message. The application prints out the To, Cc, Bcc, subject, and message from the user input when the send button is pushed. For some reasons, when the button is pushed, it gave me an error "Exception in thread "AWT-EventQueue-0"
here are my codes:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EmailWindow extends JPanel {
private JTextField to, cc, bcc, subject;
private JTextPane content;
private JButton send;
public EmailWindow() {
// Construct and add text fields for to, cc, bcc, and subject, followed
// by a Send button. You may use the createComponentWithLabel(...)
// utility method to construct a panel that includes a label and
// a text field, which can then be added to the EmailWindow panel.
// For example,
// add(createComponentWithLabel("Text", new JTextField(30));
// would add a text field next to a label with the word "Text".
add(createComponentWithLabel("to", new JTextField(30)));
add(createComponentWithLabel("cc", new JTextField(30)));
add(createComponentWithLabel("bcc", new JTextField(30)));
add(createComponentWithLabel("subject", new JTextField(30)));
// The JTextPane class supports multi-line text. For a single line
// of content text, you could use another JTextField instead.
setBackground(Color.cyan);
content = new JTextPane();
content.setPreferredSize(new Dimension(375, 200));
send = new JButton("Send");
send.addActionListener(new SendListener());
add(content);
add(send);
}
// -----------------------------------------------------------------------
// Utility method (which you may use in the constructor) that creates
// and returns a <code>JPanel</code> containing a <code>JLabel</code>
// next to an arbitrary component, such as a <code>JTextField</code>.
// -----------------------------------------------------------------------
private JPanel createComponentWithLabel(String label, Component comp) {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel(label, JLabel.RIGHT), BorderLayout.WEST);
p.add(comp, BorderLayout.CENTER);
return p;
}
// -----------------------------------------------------------------------
// Listener class to be attached to the Send button. When the button
// is pressed, the contents of the to, cc, bcc, subject, and contents
// fields will be printed to standard out.
// -----------------------------------------------------------------------
private class SendListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
System.out.println("To: " + to.getText());
System.out.println("Cc: " + cc.getText());
System.out.println("Bcc: " + bcc.getText());
System.out.println("Subject: " + subject.getText());
System.out.println("Message content: "+content.getText());
System.out.println(content.getText());
}
}
}
Main class :
import javax.swing.JFrame;
public class email {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create a frame
JFrame frame = new JFrame("Compose Message");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create an instance of EmailWindow and add it to the frame.
EmailWindow email = new EmailWindow();
frame.getContentPane().add(email);
// Set a reasonable starting size for the frame. Note that we
// do not use pack() here, since doing so with the default layout
// manager would produce a very long frame. Other layout managers
// (which will be discussed in Chapter 6) would solve this problem
// in a more flexible way.
frame.setSize(425, 400);
// Show the frame.
frame.setVisible(true);
}
}
error :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at hw6.EmailWindow$SendListener.actionPerformed(EmailWindow.java:59)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Your to, cc, bcc, subject JTextField are null .
You never initialize them , and you probably want to pass them as parameters in this part :
add(createComponentWithLabel("to", new JTextField(30)));
add(createComponentWithLabel("cc", new JTextField(30)));
add(createComponentWithLabel("bcc", new JTextField(30)));
add(createComponentWithLabel("subject", new JTextField(30)));
I would suggest :
to = new JTextField(30);
cc = new JTextField(30);
bcc = new JTextField(30);
subject = new JTextField(30);
add(createComponentWithLabel("to", to));
add(createComponentWithLabel("cc", cc));
add(createComponentWithLabel("bcc", bcc));
add(createComponentWithLabel("subject", subject));

Simple Java Calculator Logic

I'm new to programming and I was making a calculator with only 1 textfield.
I need a method which can recognize which string characters from these (+ , - , * , /)
to send the result to a variable and when i click the = button it shows the result.
I have tried to write something like that (1+2) and save it to variable then then when I try to press = button to settext the variable it shows a privilage error.
Here is the code
JButton btnOne = new JButton("1");
btnOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sum+=1;
txtoprtn.setText(txtoprtn.getText()+"1");
JButton btnTwo = new JButton("2");
btnTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sum+=2;
txtoprtn.setText(txtoprtn.getText()+"2");
}
});
JButton btnAdd = new JButton("+");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
txtoprtn.setText(txtoprtn.getText()+"+");
}
});
JButton btnEqual = new JButton("=");
btnEqual.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x = Integer.parseInt(txtoprtn.getText());
txtoprtn.setText(Integer.toString(x));
}
}
);
and this is the error
**Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "1+2"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.jadv.day01.tasks.AdvCalc$11.actionPerformed(AdvCalc.java:140)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)**
any suggestions????
First problem
When you try to just write a string statement of "1+2", what do you expect will happen? It can't simply just be evaluated like that. You would have to first use Integer.parseInt() to each of your # buttons after the number insertion is done(say, when you click the +/-///*, or =. That means the number is done and you'll get say
Integer.parseInt("123") instead of Integer.parseInt("1")+Integer.parseInt("2")+Integer.parseInt("3")
What you're trying to do is parsing a + in the middle of the parse. Keep the integer parse to the numbers and the operators stored somewhere else(explained in second problem)
Second problem
When you say "+", that doesn't parse into any operation. You would have to store the values into their individual variables and when clicked a + button, you would get a correct answer. If you want to do this without any external imports, then you would have to store the operations in a list and evaluate when = is clicked.
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
operations.add("+");//operations is a list
}
});
Solving both problems at once using an import
If you want to evaluate using a package, then use this:
ScriptEngine evaluationMachine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.eval(foo); //evaluates something like "2+1" into 3.
with the following imports:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
EDIT: By the way, though the second way is much faster, you should probably try and write it without external imports since you're new to programming. There will be inevitable situations where you're going to have to think about the problem.
The cause of the exception is that you are trying to parse a String like "1+2" to an Integer in the line:
x = Integer.parseInt(txtoprtn.getText());
You should store the numbers somewhere else, i.e. in an ArrayList.

Java program crashing when it overwrites an existing .txt file?

I'm making a simple text based game where you have to type commands to preform certain actions. I recently added a feature to the game that allows you to save your progress. But for some reason if you try to save your game over an existing save file it crashes. Here is the code that saves the game (when it fails to save it says "There was an error when trying to save game data. The game will now close." like expected):
import java.util.Formatter;
import javax.swing.JOptionPane;
public class Gamesave {
private static Formatter gamesave;
private static Formatter firstTimeSave;
private static Formatter attackpoints;
private static Formatter defensepoints;
private static Formatter skillpoints;
private static Formatter wins;
private static Formatter loses;
private static Formatter money;
// Attackpoints, defensepoints, skillpoints, wins, loses, money
public static void openFile(){
try{
attackpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_attackpoints.txt");
defensepoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_defensepoints.txt");
skillpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_skillpoints.txt");
wins = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_wins.txt");
loses = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_loses.txt");
money = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_money.txt");
gamesave = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+".txt");
firstTimeSave = new Formatter("c:\\FightNight\\Game Data\\firstTimeSave.txt");
}catch (Exception e) {JOptionPane.showMessageDialog(null, "There was an error when trying to save game data. The game will now close."); System.exit(0);}
}
public static void addRecords(){
attackpoints.format("%s",MainClass.attackpoints);
defensepoints.format("%s",MainClass.defensepoints);
skillpoints.format("%s",MainClass.skillpoints);
wins.format("%s",MainClass.wins);
loses.format("%s",MainClass.loses);
money.format("%s",MainClass.money);
firstTimeSave.format("%b", MainClass.firstTime);
}
public void closeFile(){
attackpoints.close();
defensepoints.close();
skillpoints.close();
wins.close();
loses.close();
money.close();
gamesave.close();
firstTimeSave.close();
}
}
Here is the code that calls the classes:
static class SaveAction implements ActionListener{
public void actionPerformed (ActionEvent e){
try{
Gamesave.openFile();
Gamesave.addRecords();
save.closeFile();
JOptionPane.showMessageDialog(null, "Your game has been saved.");
}catch (Exception e1) {JOptionPane.showMessageDialog(null, "Sorry, that is an invalid response.");}
}
}
Another note, when the game is launched for the first time on a computer it creates the directories for the save files and anything else needed. Thank you for any help!
The stack trace:
java.io.FileNotFoundException: c:\FightNight\Saves\null\null_attackpoints.txt (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.util.Formatter.<init>(Unknown Source)
at Gamesave.openFile(Gamesave.java:16)
at CommandLine$SaveAction.actionPerformed(CommandLine.java:93)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
It seems all your GameSave methods are static, save for the closeFile method. However all reference the same fields. Try make closeFile static. It seems to reference static fields after all.
And of course, call it like the other methods, as in: GameSave.closeFile, not someInstanceOfGameSave.closeFile.
Finally, if that doesn't work, add the line e.printStackTrace(); before showing your message dialog and print the resulting stack trace as an edit of your question.
Edit
Make sure you check for nulls in your closeFile method as well.
It is because you have nulls in your file path. Notice the first line of your error stack
java.io.FileNotFoundException: c:\FightNight\Saves\**null\null**_attackpoints.txt (The system cannot find the path specified)
There is no possible way that you can have a null in the file path name. So, with that being said, you need to go back and fix the objects that are containing the information in this part of the code. Also notice this:
at Gamesave.openFile(Gamesave.java:16)
This line tells you exactly where the error is..
So, lets check that method...
try{
attackpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_attackpoints.txt");
defensepoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_defensepoints.txt");
skillpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_skillpoints.txt");
wins = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_wins.txt");
loses = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_loses.txt");
money = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_money.txt");
gamesave = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+".txt");
firstTimeSave = new Formatter("c:\\FightNight\\Game Data\\firstTimeSave.txt");
}catch (Exception e) {JOptionPane.showMessageDialog(null, "There was an error when trying to save game data. The game will now close."); System.exit(0);}
I'm not seeing a way that this class accesses the static class "MainClass"'s newProfileName variable....so there is most likely the reason as to why you are not getting the proper information in the file name..
I'd say to update the newProfileName inside the try/catch block, to keep it up to date...
something like so
try{
MainClass.newProfileName = //accessed information from whereever you get your new profile name in the Code....
attackpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_attackpoints.txt");
defensepoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_defensepoints.txt");
skillpoints = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_skillpoints.txt");
wins = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_wins.txt");
loses = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_loses.txt");
money = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+"_money.txt");
gamesave = new Formatter("c:\\FightNight\\Saves\\"+MainClass.newProfileName+"\\"+MainClass.newProfileName+".txt");
firstTimeSave = new Formatter("c:\\FightNight\\Game Data\\firstTimeSave.txt");
}catch (Exception e) {JOptionPane.showMessageDialog(null, "There was an error when trying to save game data. The game will now close."); System.exit(0);}
The system is getting a null in the file name, which cannot be. Null means it is nothing, an d has no directory position...so find a way to update that variable, and that should fix it...
Hope this helps!

Dr Java program gets errors when writing query to MySQL Workbench

I made a program that makes a simple GUI for a login form. Just for testing purposes I made it so when you click the "Login" button, Java should just print out the query results from MySQL database. In MySQL I have a database schema called "test" and a table called "login". The login table only has 1 row: "1, angelo, password" under the columns: loginID, Username and Password.
MySQL Workbench Username is root. Host is localhost port 3306. I made sure MySQL Server is currently running (In the Task Manager Services "MYSSQLSERVER" is running)
I have the "mysql-connector-java-5.1.25-bin.jar" in my "Extra Classpath" folder for DrJava (that's the software I'm using to program).
Here is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class swing_sample extends JFrame
{
//declaring our swing components
JLabel l_name,l_pass, title;
JTextField t_name;
JPasswordField t_pass; //A special JTextField but hides input text
JButton button, button2;
Container c;
//a inner class to handling ActionEvents
handler handle;
//a separate class for processing database connection and authentication
//database db;
swing_sample()
{
super("Login form");
c=getContentPane();
//c.setLayout(new FlowLayout());
c.setLayout(null);
//extra classes
//db=new database();
handle =new handler();
//swing components
title = new JLabel("EAP Admin Log-In form");
l_name=new JLabel("Username");
l_pass=new JLabel("Password");
t_name=new JTextField(10);
t_pass=new JPasswordField(10);
button=new JButton("Login");
//adding actionlistener to the button
button.addActionListener(handle);
//add to contaienr
c.add(title);
c.add(l_name);
c.add(t_name);
c.add(l_pass);
c.add(t_pass);
c.add(button);
//visual
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,530);
//set positions, Size,
title.setLocation(175, 0);
title.setSize(200, 200);
l_name.setLocation(50, 110);
l_name.setSize(100, 100);
l_pass.setLocation(50, 210);
l_pass.setSize(100, 100);
t_name.setLocation(200, 150);
t_name.setSize(200, 25);
t_pass.setLocation(200, 250);
t_pass.setSize(200, 25);
button.setLocation(100, 400);
button.setSize(100, 25);
}
public static void main(String args[])
{
swing_sample sample=new swing_sample();
}
//an inner class .You can also write as a separate class
class handler implements ActionListener
{
//must implement method
//This is triggered whenever the user clicks the login button
public void actionPerformed(ActionEvent ae)
{
//checks if the button clicked
if(ae.getSource()==button)
{
char[] temp_pwd=t_pass.getPassword();
String pwd=null;
pwd=String.copyValueOf(temp_pwd);
System.out.println("Username,Pwd:"+t_name.getText()+","+pwd);
Connection connection = null;
try {
// Load the JDBC driver
String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver
Class.forName(driverName);
// Create a connection to the database
String serverName = "localhost:3306";
String mydatabase = "test";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username, password);
System.out.println(url);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("select Username, Password from login where loginID = 1");
while(rs.next()) {
System.out.println( rs.getString("Username"));
}
st.close();
rs.close();
connection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
// Could not find the database driver
} catch (SQLException e) {
e.printStackTrace();
// Could not connect to the database
}
//The entered username and password are sent via "checkLogin()" which return `boolean`
/* if(db.checkLogin(t_name.getText(), pwd))
{
//a pop-up box
JOptionPane.showMessageDialog(null, "You have logged in successfully","Success",
JOptionPane.INFORMATION_MESSAGE);
}
else
{
//a pop-up box
JOptionPane.showMessageDialog(null, "Login failed!","Failed!!",
JOptionPane.ERROR_MESSAGE);
}
}//if
*/
}//method
}//inner class
}//class
}
Here are the errors I am getting:
java.lang.ClassNotFoundException
at edu.rice.cs.plt.reflect.PathClassLoader.findClass(PathClassLoader.java:148)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at swing_sample$handler.actionPerformed(swing_sample.java:111)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
It seems you have not placed the mysql connector jar file in your classpath. Try adding that jar and run your program. You can download the mysql connector official jdbc jar from here:
http://dev.mysql.com/downloads/connector/j/3.1.html

Categories

Resources