java.lang.NumberFormatException: empty String - java

The code below keeps giving a java.lang.NumberFormatException: empty String:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
double AText = Double.parseDouble(angleAField.getText());
double BText = Double.parseDouble(angleBField.getText());
double CText = Double.parseDouble(angleCField.getText());
double aText = Double.parseDouble(sideaField.getText());
double bText = Double.parseDouble(sidebField.getText());
double cText = Double.parseDouble(sidecField.getText());
if (getMissing(angleAField.getText()) == false && getMissing(angleCField.getText()) == false) { //doesnt have angle C ,find Angle A
double angleA = Math.round(Math.asin((Math.sin(BText) / bText) * aText));
angleAField.setText("" + angleA);
}
}
public boolean getMissing(String Field) {
try {
if (Field.equals("")) {
return false; // has number
}
} catch (NumberFormatException e) {}
return true;
}
Error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011)
at java.lang.Double.parseDouble(Double.java:540)
at sowhatstrig.trigFrame.jButton4ActionPerformed(trigFrame.java:520)
at sowhatstrig.trigFrame.access$300(trigFrame.java:20)
at sowhatstrig.trigFrame$4.actionPerformed(trigFrame.java:353)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:696)
at java.awt.EventQueue$4.run(EventQueue.java:694)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

You should check your field before parse double:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
double AText = ParseDouble(angleAField.getText());
double BText = ParseDouble(angleBField.getText());
double CText = ParseDouble(angleCField.getText());
double aText = ParseDouble(sideaField.getText());
double bText = ParseDouble(sidebField.getText());
double cText = ParseDouble(sidecField.getText());
// other code here same
}
double ParseDouble(String strNumber) {
if (strNumber != null && strNumber.length() > 0) {
try {
return Double.parseDouble(strNumber);
} catch(Exception e) {
return -1; // or some value to mark this field is wrong. or make a function validates field first ...
}
}
else return 0;
}

The string you're trying to parse as double is empty. You need to check if the getText() method returns a non empty string before trying to do the parsing cause you can't parse to double an empty string.

Related

Why is my database arraylist population algorithm throwing an error?

This is my populate account method which takes the values from my database columns and stores them within an arraylist of objects of the account class that i made which has fields like username and password.
The second part of the code will show if you scroll down
private ArrayList<account> populateAccount() throws SQLException{
Connection c = DatabaseUtilityClass.createNewConnection();
ArrayList<account> list = new ArrayList();
try{
String q = "Select * from LOGIN";
Statement stmt = (Statement)c.createStatement();
try(ResultSet rs= stmt.executeQuery(q)){
while(rs.next()){
account a = new account();
a.setUsername(rs.getString("USERNAME"));
a.setPassword(rs.getString("PASSWORD"));
list.add(a);
}
}
}
catch(Exception e){
e.printStackTrace();
System.out.println("err");
}
c.close();
return list;
}
This is the second part of my code which should store the arraylist of objects filled with the database info and then take user text and use a for each loop to iterate through each object checking if the username and password values are the same as the one the user entered via a jTextfield and password field. The errors are on the bottom.
private void LoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
accountCheck= populateAccount();
} catch (SQLException ex) {
Logger.getLogger(LoginPage.class.getName()).log(Level.SEVERE, null, ex);
}
String username = user.getText();
String password = pass.getText();
for (account a:accountCheck) {
if(a.getUsername().equals(username) && a.getPassword().equals(password)){
JPanel p = (JPanel)this.getParent();
CardLayout c = (CardLayout)p.getLayout();
c.show(p, PanelConstants.Home);
}
}
}
java.lang.UnsupportedOperationException: Not supported yet.
at boomiautomationapp.account.<init>(account.java:21)
at boomiautomationapp.LoginPage.populateAccount(LoginPage.java:50)
at boomiautomationapp.LoginPage.LoginActionPerformed(LoginPage.java:146)
at boomiautomationapp.LoginPage.access$000(LoginPage.java:28)
at boomiautomationapp.LoginPage$1.actionPerformed(LoginPage.java:94)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
at java.awt.EventQueue.access$300(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:706)
at java.awt.EventQueue$3.run(EventQueue.java:704)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:720)
at java.awt.EventQueue$4.run(EventQueue.java:718)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

trouble in the database and checking the database in java

I am having trouble in checking the username in the ms access database
java.sql.SQLException: No data found
here is the database connect
public class dbAccess
{
Connection conn;
ResultSet rs;
Statement s;
PreparedStatement ps;
public void doConnect()
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String login = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=E:\\File Kuliah\\Semester 7\\AOOP\\JavaApplication1\\build\\classes\\Database1.accdb";
conn = DriverManager.getConnection(login);
System.out.println("Connected");
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
and here is the code that has the error
private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {
try
{
db.ps = db.conn.prepareStatement("SELECT * FROM DatabaseAOOP");
db.rs = db.ps.executeQuery();
System.out.print("1");
while(db.rs.next())
{
if(userRegis.getText().equals(db.rs.getString("username")))
{
System.out.print("3");
JOptionPane.showMessageDialog(this, "Username is already exists !");
userRegis.setText("");
passRegis.setText("");
//db.rs=null;
//db.ps=null;
break;
}
else if(userRegis.getText().isEmpty())
{
JOptionPane.showMessageDialog(this, "Please input the name");
}
else if(!userRegis.getText().equals(db.rs.getString("username")))
{
JOptionPane.showMessageDialog(this, "Searching ...");
}
else
{
System.out.print("2");
db.ps = db.conn.prepareStatement("INSERT INTO DatabaseAOOP(username,password) VALUES(?,?)");
db.s = db.conn.createStatement();
db.ps.setString(1, userRegis.getText());
db.ps.setString(2, passRegis.getText());
db.ps.executeUpdate();
JOptionPane.showMessageDialog(this, "Thank you for registering !");
userRegis.setText("");
passRegis.setText("");
break;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println(ex);
}
}
here are the printstacktrace
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3914)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5697)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:353)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:410)
at Frame.registerButtonActionPerformed(Frame.java:277)
at Frame.access$600(Frame.java:4)
at Frame$7.actionPerformed(Frame.java:135)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
actually i just checked the database connected, but there is no data found
Immediately after entering the while(db.rs.next()) loop you call db.rs.getString("username"), then later in the loop you call db.rs.getString("username") again. It is the second invocation that throws the "No data found" exception.
In many cases JDBC will only let us call get... methods once per column for a given (current) row in the ResultSet. You should save the value to a String
String theUserName = db.rs.getString("username");
and then use the String variable for your (multiple) comparisons.

Adding FeatureCollection to a FeatureStore throwing AbstractMethodError

This method is supposed to replace the features in the database with new features I pass to it.
private static void replaceBoundaryShape(FeatureCollection<SimpleFeatureType, SimpleFeature> dbFeatures) throws IOException, CQLException{
FeatureStore<SimpleFeatureType, SimpleFeature> fs = null;
FeatureSchemaFactory factory = FeatureSchemaFactory.init();
DataStore geoStore = initDataStore();
try{
fs = (FeatureStore) geoStore.getFeatureSource(factory.getFieldFeatureSchema().getTypeName());
fs.setTransaction(new DefaultTransaction());
for(FeatureIterator<SimpleFeature> iterator = dbFeatures.features(); iterator.hasNext();){
SimpleFeature simpleFeature = iterator.next();
Number fieldId = (Number) simpleFeature.getAttribute(FeatureSchemaFactory.FIELD_ID);
Filter filter = createSearchByIdFilter(fieldId.longValue());
fs.removeFeatures(filter);
}
fs.addFeatures(dbFeatures);
fs.getTransaction().commit();
}catch(CQLException ex){
throw new CQLException(ex.getMessage());
}
}
this is where I create the feature collection passed to replace boundary shape
private static FeatureCollection<SimpleFeatureType, SimpleFeature> createBoundaryFeatures(SimpleFeatureType dbSchema, Collection<FieldFeature> fields){
List<SimpleFeature> result = new ArrayList<SimpleFeature>(fields.size());
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(dbSchema);
for(FieldFeature f: fields){
builder.set("BNDRS", f.getGeometries());
builder.set("FIELD", f.getField());
builder.set("FID", f.getFid());
builder.set("GROWER", f.getGrower());
builder.set("SIMPLIFIED_BNDRS", f.getSimplifiedGeometries());
result.add(builder.buildFeature(null));
}
return DataUtilities.collection(result);
}
This is where I get my field features from a file path and a specified field:
private static Collection<FieldFeature> convertShpFile(String filePath, Field field) throws MalformedURLException, IOException{
#SuppressWarnings("deprecation")
ShapefileDataStore source = new ShapefileDataStore(new File(filePath).toURL());
Collection<FieldFeature> result = new LinkedList<FieldFeature>();
DefaultQuery query = new DefaultQuery();
query.setCoordinateSystemReproject(DefaultGeographicCRS.WGS84);
FeatureCollection queryResult = source.getFeatureSource().getFeatures(query);
FeatureIterator<SimpleFeature> fi = queryResult.features();
while(fi.hasNext()){
SimpleFeature feature = fi.next();
FieldFeature fieldFeature = new FieldFeature();
Object defaultGeometry = feature.getDefaultGeometry();
if(defaultGeometry instanceof Polygon){
Polygon polygon = (Polygon) defaultGeometry;
Polygon[] polygons = {polygon};
defaultGeometry = geometryFactory.createMultiPolygon(polygons);
}
fieldFeature.setField(field.getId());
fieldFeature.setGeometries(defaultGeometry);
fieldFeature.setSimplifiedGeometries(GeoHelper.simplifyGeometry((Geometry) defaultGeometry));
result.add(fieldFeature);
}
fi.close();
source.dispose();
return result;
}
The error occurs on the fs.addFeatures(dbFeatures) line of the replaceBoundaryShape method.
Removing features does not throw an error, but when I call the addFeatures function I receive this AbstractMethodError:
java.lang.AbstractMethodError: org.geotools.jdbc.PreparedStatementSQLDialect.setGeometryValue(Lcom/vividsolutions/jts/geom/Geometry;IILjava/lang/Class;Ljava/sql/PreparedStatement;I)V
The error appears to be thrown when the features are being inserted into the JDBCDataStore
EDIT: Here is the full stack trace
java.lang.AbstractMethodError: org.geotools.jdbc.PreparedStatementSQLDialect.setGeometryValue(Lcom/vividsolutions/jts/geom/Geometry;IILjava/lang/Class;Ljava/sql/PreparedStatement;I)V
at org.geotools.jdbc.JDBCDataStore.insertSQLPS(JDBCDataStore.java:4005)
at org.geotools.jdbc.JDBCDataStore.insert(JDBCDataStore.java:1582)
at org.geotools.jdbc.JDBCDataStore.insert(JDBCDataStore.java:1545)
at org.geotools.jdbc.JDBCInsertFeatureWriter.write(JDBCInsertFeatureWriter.java:76)
at org.geotools.data.InProcessLockingManager$1.write(InProcessLockingManager.java:337)
at org.geotools.data.store.ContentFeatureStore.addFeature(ContentFeatureStore.java:309)
at org.geotools.data.store.ContentFeatureStore.addFeatures(ContentFeatureStore.java:263)
at com.conserviscorp.shape.upload.FieldDAO.replaceBoundaryShape(FieldDAO.java:146)
at com.conserviscorp.shape.upload.FieldDAO.updateFieldData(FieldDAO.java:116)
at com.conserviscorp.ui.MatchedFieldFrame$2.actionPerformed(MatchedFieldFrame.java:83)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
The issue was that I was using the wrong version of geotools. When adding items to the dependencies I was using the 10-beta version in some parts, and the current version in other parts.

exception thrown while using .txt in file name

I am trying to run the following code in which i have to save my file as .txt...but whenever I click on 'Save' button..it throws an exception..
Also i want to know how could I save the contents of my textarea line by line in the txt file (including \n).
Here is the code
try
{
int val = jfc.showSaveDialog(jf);
int x =0;
String line;
if(val == JFileChooser.APPROVE_OPTION)
{
File fs=jfc.getSelectedFile();
if(!fs.exists())
{
fs.createNewFile();
FileWriter fw=new FileWriter(fs.getAbsolutePath()+".txt");
BufferedWriter bf=new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new StringReader(ja.getText()));
while((line= br.readLine())!=null)
{
x++;
if(line.charAt(x)=='\n')
fw.write('\n');
else
fw.write(line+"\n");
}
fw.close();
}
else
{
}
}
}
catch(Exception e2)
{
e2.printStackTrace();
JOptionPane.showMessageDialog(null,"Cannot save file");
}
java.lang.StringIndexOutOfBoundsException: String index out of range: 3
at java.lang.String.charAt(String.java:658)
at notepad$1.actionPerformed(notepad.java:100)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.AbstractButton.doClick(AbstractButton.java:376)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:833)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:877)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3320)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Change your current code from
while((line= br.readLine())!=null)
{
x++;
if(line.charAt(x)=='\n')
fw.write('\n');
else
fw.write(line+"\n");
}
to
while((line= br.readLine())!=null) {
fw.write(line+"\n");
}
You are checking the first char in the first line, the second char in the second line so on.
Try changing
if(line.charAt(x)=='\n')
to
if(line.endsWith('\\n'))
Also you should escape line ends. Use \\n instead of \n.

data not saving in database through jtable (Edited)

i have made a jtable where i am giving the values manually,and saving the data in the sql by clicking the save(jButton2) button.now the problem is that when i am keeping the jtable blank and saving it..its showing data saved,but nothing is saving in the database.
And when i am putting the data in the jtable and trying to save its giving exception.
column(i,5) is getting value by multiplying column(i,3) and column(i,4)
jButton2ActionPerformed(save button) method is as follows:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
String sql="insert into `sampleDB`.`Item_detail` (P_name,Manuf_name,Model_no,Purchase_price,Available,total Price,Sell_price,Quality,Color,Description,profit,Cost_price,idDealerItem) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
pst=con.prepareStatement(sql);
int last=jTable1.getRowCount();
for( int i=0;i<last;i++){
if(((String) jTable1.getValueAt(i,0))!=null){
String column1= (String) jTable1.getValueAt(i,0);
String column2= (String) jTable1.getValueAt(i,1);
String column3= (String) jTable1.getValueAt(i,2);
String column4= (String) jTable1.getValueAt(i,3);
String column5= (String) jTable1.getValueAt(i,4);
String column6= (String) jTable1.getValueAt(i,5);
String column7= (String) jTable1.getValueAt(i,6);
pst.setString(1,column1);
pst.setString(2,column2);
pst.setString(3,column3);
pst.setString(4,column4);
pst.setString(5,column5);
pst.setString(6,column6);
pst.setString(7,null);
pst.setString(8,column7);
pst.setString(9,null);
pst.setString(10,null);
pst.setString(11,null);
pst.setString(12,null);
pst.setString(13,null);
pst.execute();
}
}
JOptionPane.showMessageDialog(null, "data saved");
}
catch(Exception e) {
e.printStackTrace();
}
Method where columns are getting multiplied is as follow.:
private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(evt.getKeyCode()==KeyEvent.VK_TAB){
int r = jTable1.getRowCount();
for (int i = 0; i < r; i++){
if(jTable1.getValueAt(i,3)!=null && jTable1.getValueAt(i,4)!=null ){
int a=Integer.parseInt(jTable1.getValueAt(i,3).toString());
int b=Integer.parseInt(jTable1.getValueAt(i,4).toString());
int d= a*b;
jTable1.setValueAt(d,i,5);
}
}
}
}
new error is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Price,Sell_price,Quality,Color,Description,profit,Cost_price,idDealerItem) value' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1364)
at Extra.jButton2ActionPerformed(Extra.java:331)
at Extra.access$300(Extra.java:14)
at Extra$4.actionPerformed(Extra.java:121)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3311)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Please help..
thanks in advance..
You have ClassCastException because of your JTable store Integer values which can't be cast to String like next String column1= (String) jTable1.getValueAt(i,0);. Change that to:
String column1= jTable1.getValueAt(i,0) == null ? "" : jTable1.getValueAt(i,0).toString();
You can't cast Integer to String, but you can write
Integer integer = new Integer(4);
String string = integer.toString(); // "4"

Categories

Resources