How to fix error using equalsIgnorecase in java netbeans? - java

I am building java project in inventory management. following is the code i used for inserting color in database using equalsIgnorecase but it continuous showing Already exist. Please some one fix my code.
thanks
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
if(txtNewColor.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Fields should not be empty");
}
else
{
try {
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(cl));
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
if (color==0)
{
String strdata="Insert into color_details (Color)values(?)";
ps=DbConnection.cn.prepareStatement(strdata);
ps.setString(1, txtNewColor.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Color Added Successfully");
cleartext();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
refreshTable();
}

Try change if(cl.equalsIgnoreCase(cl)); to if(c.equalsIgnoreCase(cl))
Had not spotted the semi-colon at the end of your if statement

You are comparing the same String again. So It always results in a true, also the ; will skip even if they match. Remove it.
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(c))
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}

You used same two strings to compare. so change c.equalsIgnoreCase(c1). Also make sure you have removed trailing spaces when getting input from text fields. it may makes your comparison fail.
String c = txtNewColor.getText().trim();
Remove the semi colon after if clause
if(cl.equalsIgnoreCase(cl)); ---> if(cl.equalsIgnoreCase(cl))

Related

Showing an Integer tableview in javaFx as a string

I am trying to show a tableview where when the value in the table is a integer like 1 for example I want to display a String. So far I tried to get the cellValue like this:
public void changeView() {
if(intervall.getCellFactory().call(intervall).equals(1)) {
intervall.getCellFactory().call(intervall).setText("Täglich");
}
}
And I am calling the method in my initialize after setting the cellvalue.
public void initializeTable() {
try {
// Ablesen
Statement pStatement = connection.createStatement();
flightList = FXCollections.observableArrayList();
ResultSet myRs = pStatement
.executeQuery("select * from fluglinie where fluggesellschaft =\"" + fluggesellschaft + "\"");
while (myRs.next()) {
flightList.add(new flightRouteAddModel(myRs.getString("startFlughafen"),
myRs.getString("zielFlughafen"), myRs.getString("startDatum"), myRs.getString("flugzeug"),
myRs.getInt("intervall"), myRs.getInt("anzahlEconomy"), myRs.getInt("anzahlBusiness"),
myRs.getFloat("preisEconomy"), myRs.getFloat("preisBusines"), myRs.getFloat("distanz")));
}
} catch (Exception e) {
System.out.println(e);
}
startAirport.setCellValueFactory(new PropertyValueFactory<>("startAirport"));
targetAirport.setCellValueFactory(new PropertyValueFactory<>("targetAirport"));
flightDate.setCellValueFactory(new PropertyValueFactory<>("flightDate"));
airplane.setCellValueFactory(new PropertyValueFactory<>("airPlane"));
intervall.setCellValueFactory(new PropertyValueFactory<>("intervall"));
seatCountEco.setCellValueFactory(new PropertyValueFactory<>("countEconomy"));
seatCountBus.setCellValueFactory(new PropertyValueFactory<>("countBusiness"));
priceEco.setCellValueFactory(new PropertyValueFactory<>("priceEconomy"));
priceBus.setCellValueFactory(new PropertyValueFactory<>("priceBusiness"));
distance.setCellValueFactory(new PropertyValueFactory<>("distance"));
table.setItems(flightList);
changeView();
}
But it is not working can someone maybe take a look at this? I know changing the db would be maybe a better solution but I kinda wanted to try this workaround
The cellFactory returns TableCells. Calling this yourself does not result in a cell that is part of the TableView (or becomes part of it). Any TableCell with a properly impelemented equals method never yields true, if 1 (or any other Integer) is passed.
Assuming you always want to display Täglich instead of 1, the way to go about this is using a custom cellFactory for this column:
intervall.setCellFactory(col -> new TableCell<flightRouteAddModel, Integer>() {
#Override
protected void updateItem(Integer item, boolean empty) {
String text = "";
if (item != null) {
switch(item) {
case 1:
text = "Täglich";
break;
case 7:
text = "Wöchentlich";
break;
default:
text = String.format("Alle %d Tage", item);
break;
}
}
setText(text);
}
});
BTW: Please learn about the java naming conventions. This makes the code easier to read for other people and it should make this more readable even for yourself, since all java APIs (that I know of) use these conventions: Type names start with an uppercase letter.

How to check if JRadioButtons are selected?

I tried
if(jRadioButton1.isSelected() ||(jRadioButton2.isSelected()) {
jGenderGroup.getSelection().getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.")
}
But controller doesn't stop after highlighted line it does go ahead to final line and throw NullPointerException
customers.setGender(jGenderGroup.getSelection().getActionCommand());
Where customers is POJO class.
How I can get rid of this?
try this :)
jRadioButton1.setActionCommand("Male");
jRadioButton2.setActionCommand("Female");
if(!jGenderGroup.isChecked()){
jLable1.setText("Please Select Gender");
}
if(jRadioButton1.isSelected())
{
//Male
}
else if(jRadioButton2.isSelected())
{
//Female
}
else
{
// no radio button has been selected
}
or alter your code like
if(jGenderGroup.getSelection() != null)
{
customer.setGender(jGenderGroup.getSelection().getActionCommand())
} else {
jGndrErrorLabel.setText("Select gender.")
}
I simply removed ButtonGroup jGenderGroup
and perform conditions for jRadioButton1 and jRadioButton2 at last instead of middle and as I had commented I can not set String gender = new String(); as
gender = jRadioButton1.getActionCommand();
Within conditional block because of POJO
So I just tricked that put it at the end like this :
String gender = new String();
if (jRadioButton1.isSelected()) {
gender = jRadioButton1.getActionCommand();
} else if (jRadioButton2.isSelected()) {
gender = jRadioButton2.getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.");
jGndrErrorLabel.setForeground(Color.red);
}
That's what I expected
Thanks for all of your time and efforts.

Java returning null pointer exception for SQL query that gets passed to JSP

I am working on a school assignment that required us to use SQL statements in Java code as well as use the LIKE operator for a search. In order to properly search I have to get a string from the user, and split the string by any delimiter, and then run the query like so:
SELECT * FROM movies WHERE (movies.title LIKE '%userInput%');
I then return this query in the form of an ArrayList.
Now, when I was testing it out. I originally tested it with no user input, and my query became: SELECT * FROM movies WHERE (movies.title LIKE '%%');. This gave me the correct results.
However when I put a title in there, all of the sudden I get a NullPointerException on this line:
if(title.equals("")) { return "(movies.title LIKE '%%') "; from this section of my code:
public String getSearchString(String title) {
if(title.equals("")) { return "(movies.title LIKE '%%') "; }
String ret = "(";
ArrayList<String> titleArray = Util.splitSearch(title);
for(int i = 0; i < titleArray.size() - 1; ++i) {
String temp = titleArray.get(i);
String stmt = "movies.title LIKE '%" + temp + "%' OR ";
ret += stmt;
}
String temp = "movies.title LIKE '%" + titleArray.get(titleArray.size() - 1) + "%')";
ret += temp;
return ret;
}
This is then called like so:
public List<Movie> listMovies(String title) throws SQLException {
List<Movie> search = new ArrayList<Movie>();
if(null != title && title.isEmpty()) { title = ""; }
ResultSet res = queryMovies(getSearchString(title));
while(res.next()) {
Movie mov = new Movie();
mov.setTitle(res.getString("title"));
search.add(mov);
}
return search;
}
private static queryMovies(String st) throws SQLException {
ResultSet res = null;
try {
PreparedStatement ps = dbcon.prepareStatement(st);
res = ps.executeQuery();
} catch(SQLException e) {
e.printStackTrace();
}
return res;
}
I unfortunately have to do this since I won't know how much a user will enter. And I am also not allowed to use external libraries that make the formatting easier. For reference my Util.splitSearch(...) method looks like this. It should be retrieving anything that is a alphanumeric character and should be splitting on anything that is not alphanumeric:
public static ArrayList<String> splitSearch(String str) {
String[] strArray = str.split("[^a-zA-Z0-9']");
return new ArrayList(Arrays.asList(strArray));
}
What is interesting is when I pass in getSearchString(""); explicitly, I do not get a NullPointerException. It is only when I allows the variable title to be used do I get one. And I still get one when no string is entered.
Am I splitting the String wrong? Am I somehow giving SQL the wrong statement? Any help would be appreciated, as I am very new to this.
the "title" which is passed from input is null, hence you're getting nullpointerexception when you do title.equals("").
Best practices suggest you do a null check like (null != title && title.equals("")).
You can also do "".equals(title)

String.length() gives me a wrong value

Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.

Adding Values to database through Netbeans

I get an SQLexception error Coloumn Count does not match value count at row 1.
I have tried altering the databse as checked the statements accordinly but fail to recognise the issue. Anny suggestions please...
JButton btnNewButton_1 = new JButton("Save");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String PHN = textField_a.getText();
String Week1 = textField_4.getText();
String Week2 = textField_5.getText();
String Week3 = textField_6.getText();
String Week4 = textField_7.getText();
if (PHN.equals("") || (Week1.equals("") || (Week2.equals("") || (Week3.equals("") || (Week4.equals("") ))))) {
JOptionPane.showMessageDialog(frmTemplate, "Please enter values in all the fields.");
}
else {
try {
db.stmt.executeUpdate("INSERT INTO weight (PHN, Week1, Week2, Week3, Week4)"+"VALUES"+"("+"'"+PHN+"',"+"'"+Week1+"',"+"'"+Week2+"'"+"'"+Week3+"'"+"'"+Week4+"')");
JOptionPane.showMessageDialog(frmTemplate, "New Record Added");
textField_a.setText(null);
textField_4.setText(null);
textField_5.setText(null);
textField_6.setText(null);
textField_7.setText(null);
}
catch (SQLException e) {
JOptionPane.showMessageDialog(frmTemplate, "The value you have entered already exist");
e.printStackTrace();
}
}
}
});
It looks like you're missing a few commas. Try looking into the PreparedStatement class to create you're statements. It's a lot easier to work with than trying to build strings of your query and it protects you from sql injection. Good luck!

Categories