i can't figure out how to tell the user that there is "no such title found" when they go to search for a title. when i test it and type in a title from the database it shows the correct information:
Game Id: 2
Title: Goldeneye 007
Rating: T
Platform: Nintendo 64
Developer: RockStar
but if i type in random information the output looks like this:
Game Id: 0
Title: asdsdfdfg
Rating: null
Platform: null
Developer: null
i'm using a basic console application in java with mysql i have two layers.
my presentation layer:
private static Games SearchForGame() {
Logic aref = new Logic();
Games g = new Games();
#SuppressWarnings("resource")
Scanner scanline = new Scanner(System.in);
System.out.println("Please enter the name of the game you wish to find:");
g.setTitle(scanline.nextLine());
aref.SearchGame(g);
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
return g;
}
and a logic layer
public Games SearchGame(Games g) {
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
String sql = "SELECT GameId,Title,Rating,Platform,Developer FROM games WHERE Title=?";
java.sql.PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, g.getTitle());
ResultSet rs = statement.executeQuery();
while(rs.next()){
g.setGameId(rs.getInt("GameId"));
g.setTitle(rs.getString("Title"));
g.setRating(rs.getString("Rating"));
g.setPlatform(rs.getString("Platform"));
g.setDeveloper(rs.getString("Developer"));
}
} catch (Exception e) {
e.printStackTrace();
}
return g;
}
Use an if statement?
if(g.getRating() != null /*or g.getGameId() == 0 or many other things*/) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
} else {
System.out.println();
System.out.println("No such title found");
//throw some sort of exception (and plan to catch it) so that you
//can get out of this method without returning g full of null values
}
return g;
You can do that in many ways, will explain one here.
In SearchGame method use isBeforeFirst() method to check if you have any data at all.
if(!resultSet.isBeforeFirst()){
return null;
}
And in your SearchForGame() if the object is null, display a message.
if(g != null) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
System.out.println("Title: " + g.getTitle());
System.out.println("Rating: " + g.getRating());
System.out.println("Platform: " + g.getPlatform());
System.out.println("Developer: " + g.getDeveloper());
} else {
System.out.println("No data found");
}
Checking nulls is a bad form of flow control. You should consider a boolean result instead.
if(aref.SearchGame(g)) {
System.out.println();
System.out.println("Game Id: " + g.getGameId());
. . .
else {
System.out.println("No such title found");
}
Then in your logic, just do this:
public boolean SearchGame(Games g) {
boolean found = false;
try {
[your sql select here]
if (rs.next()) {
[access result set]
found = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return found;
}
But an even better way is to return a list of Game instance and then check if that list is empty, like this.
List<Game> SearchGames(String title)
That's a good solid API, and you could use it like this:
List<Game> games = aref.SearchGames(title);
if(games.size() > 0) {
Game g = games.get(0);
System.out.println();
System.out.println("Game Id: " + g.getGameId());
. . .
else {
System.out.println("No such title found");
}
This also allows you to find multiple Games with similar titles if you wanted.
Related
I want to add new room, I would type the room details, Room Number, Room type, Bed number and Rates into the text fields, when I click save, I get the error java.lang.NumberFormatException: For input string: ""
The error originates from at RoomMang.jButton1ActionPerformed(RoomMang.java:352) which is fetchFromTextF(); function. See Image :
My insert statement using System.out.println (insertquery); looks like this:
insert into roomdetail(room_no,room_type,room_rate,room_bed)values('','','','');
This is how i fetch the data from the textfields:
public void fetchFromTextF(){
rno=rnumber.getText();
rtype=jTextField2.getText();
rrate=Integer.parseInt(jTextField3.getText());
rbed=jTextField4.getText();
}
And this is my save action performed button:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
clearTextF();
enableTextF();
String query = "SELECT * FROM roomdetail where room_no like '" + rnumber.getText() + "';";
smt = con.createStatement();
rs1 = smt.executeQuery(query);
if (!rs1.next()) {
try {
if (evt.getActionCommand().equals("Save")) {
fetchFromTextF();
int code = JOptionPane.showConfirmDialog(this, "Information of Room No." +rno+ " will be added in database.", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (code == JOptionPane.YES_OPTION) {
String insertquery = "insert into roomdetail(room_no,room_type,room_rate,room_bed)values('" +rno + "','" + rtype + "'," + rrate + ",'" + rbed + "');";
smt = con.createStatement();
int success = smt.executeUpdate(insertquery);
if (success > 0) {
JOptionPane.showMessageDialog(this, "Record Saved");
jButton1.setText("New");
} else {
JOptionPane.showMessageDialog(this, "Problem in Saving. Retry");
}
} else {
}
} else if (evt.getActionCommand().equals("New")) {
clearTextF();
jButton1.setText("Save");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(this, "Room No. already used, Give another Room No.");
}
} catch (Exception ex) {
}
}
The value in jTextField3 is blank so the below will fail
rrate=Integer.parseInt(jTextField3.getText());
maybe change to
rrate = -1;
if (jTextField3.getText().trim().length() > 0) {
rrate=Integer.parseInt(jTextField3.getText());
}
or simply catch the exception
try {
rrate=Integer.parseInt(jTextField3.getText().trim ());
}
catch (NumberFormatException ex) {
System.err.println (ex);
rrate = -1;
}
For a few projects, I've been trying to make a console menu in Java similar to:
(1) Do this
(2) Do that
(3) Blah blah
(4) etc
I'm using a do {...} while (...) loop but I can't get the right value for the controlling variable.
The code I had was:
String status = "e";
do {
System.out.println("---------------------------------------");
System.out.println(b1.toString());
System.out.println(b2.toString());
System.out.println(b3.toString());
System.out.println("---------------------------------------");
System.out.println("Borrow(b), Return(r), Check(c), Exit(e)");
status = r.nextLine();
....
} while(!status.equals("e"));
This code resulted in all the printlns outputting correctly, but upon pressing enter, the same thing would output again and the code I replaced with .... will not excute. This code had other console outputs which never came about.
I thought this was because the value returned by r.nextLine() continually changes as new data gets outputted. So I made a separate static function:
public static String getInfo(Scanner r, Book b1, Book b2, Book b3) {
System.out.println("---------------------------------------");
System.out.println(b1.toString());
System.out.println(b2.toString());
System.out.println(b3.toString());
System.out.println("---------------------------------------");
System.out.println("Borrow(b), Return(r), Check(c), Exit(e)");
String status = r.nextLine();
return status;
}
But this function also returns the same result. What can I do to fix this problem?
Edit:
Right now, this is my full code for the menu portion, this runs in the main.
`String status = "e";
do {
status = getInfo(reader,b1,b2,b3);
if (status == "b") {
System.out.println("Which patron ( (1)" + p.getName() + " or (2)" + p2.getName() + " is borrowing?");
int cur = reader.nextInt();
System.out.println("Which book is " + cur + " borrowing?");
String curbk = reader.nextLine();
if (p.hasBook(curbk)){
System.out.println(p.getName() + " has this book already.");
} else {
if (p2.hasBook(curbk)) {
System.out.println(p2.getName() + " has this book already.");
} else {
if (cur==1) {
System.out.println(p.borrowBook(curbk));
} else {
System.out.println(p2.borrowBook(curbk));
}
}
}
} else if (status == "r") {
System.out.println("Which patron ( (1)" + p.getName() + " or (2)" + p2.getName() + ") is returning?");
int cur = reader.nextInt();
System.out.println("Which book is " + cur + " returning?");
String curbk = reader.nextLine();
if (cur==1) {
if (p.hasBook(curbk)){
System.out.println(p.returnBook(curbk));
} else {
System.out.println(p.getName() + " does not have this book.");
}
} else {
if (p2.hasBook(curbk)){
System.out.println(p2.returnBook(curbk));
} else {
System.out.println(p2.getName() + " does not have this book.");
}
}
} else if (status == "c") {
System.out.println("Which book would you like to check for?");
String curbk = reader.nextLine();
if (p.hasBook(curbk)){
System.out.println(p.getName() + " has this book.");
} else {
if (p2.hasBook(curbk)) {
System.out.println(p2.getName() + " has this book.");
} else {
System.out.println("This book is ready to be checked out!");
}
}
}
} while(!status.equals("e"));`
The getInfo() is from above.
String status = r.nextLine();
Remove the keyword String, as it's creating a new String rather than using the variable you already created.
As the title says. I have trouble in Returning a value that says "Not Found",
When i try to input a value that is not in range.
PS: I'm new here so be gentle. hehe
public static void checkStatus(String ID_No) throws SQLException{
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
}
}
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
}
}
Take that if-else condition in a method which returns a String "NOT FOUND".
Change
public static void checkStatus(String ID_No) throws SQLException{
to
public static String checkStatus(String ID_No) throws SQLException{
then return a String whether successful or "Not Found"
So, essentially when rs.next holds, then that means that there is some sort of value that is found when the query is executed.
RS.next returns a boolean, and using that boolean you can do something like this.
boolean isFound = rs.next();
if(isFound)
{
// your while loop
// at the end of your while loop add isFound = rs.next()
}
else
{
return "Not Found";
}
It depends on what you want to happen when a student is not found here is 2 ways you could do it.
Throw an exception (this would be if it is an error if a student doesnt exist)
try {
checkStatus("studentA");
} catch(StudentNotFoundException e) {
System.out.println("Student wasnt found!");
}
public static void checkStatus(String ID_No) throws SQLException, StudentNotFoundException {
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return;
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return;
}
}
throw new StudentNotFoundException(); // create this exception eg: class StudentNotFoundException extends Exception
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
}
}
Or you could return a value
int exists = checkStatus("studentA");
if(exists == 0)
System.out.println("Student wasnt found");
public static int checkStatus(String ID_No) throws SQLException{
try{
ResultSet rs;
String validStatus = "SELECT * FROM validation";
st = connection.createStatement();
rs = st.executeQuery(validStatus);
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if (!getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
return 1; // found
} else if (getValidStatus.equals("Accepted") && getStudValid.equals(ID_No)){
System.out.println("Student " + getStudValid + " You are Enrolled!");
return 1; // found
}
}
return 0; // no student found
rs.close();
} catch(SQLException e){
System.out.println("Updated "+ ID_No);
return -1; // error occured
}
}
You could develop logic like -
boolean found = false;
while(rs.next()){
getStudValid = rs.getString("ID_No");
getValidStatus = rs.getString("Validation");
if(getStudValid.equals(ID_No)){
if(getValidStatus.equals("Accepted"))
System.out.println("Student " + getStudValid + " You are Enrolled!");
else
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
found =true;
}
}
if(!found)
System.out.println("Student "+ID_No+" Not found");
But I'd recommend you to optimize this code by optimizing your query - SELECT * FROM validation where ID_No=? and also use PrepareStatement.
String validStatus = "SELECT * FROM validation where ID_No=?";
pst = connection.prepareStatement(validStatus);
pst.setString(1,Id_No);
rs = pst..executeQuery();
if(rs.next()){
if(getValidStatus.equals("Accepted"))
System.out.println("Student " + getStudValid + " You are Enrolled!");
else
System.out.println("Student " + getStudValid + " Please complete the required pre-requisite processes.");
}else
System.out.println("Student "+ID_No+" Not found");
Some related topics -
Difference between Statement and PreparedStatement
This code to search for a book or a user within databases, there is no problem when you search for a user, but when you search for a book that does not exist, it appears this error:
Error: After end of result set
if(RB1.isSelected()==true)
{
Statement stmt = (Statement)conn.createStatement();
String SQL1 = "select * from usernames";
ResultSet rs1 = stmt.executeQuery(SQL1);
String ID ="";
while(rs1.next())
{
ID = rs1.getString("UserID");
if(UIorBItf.getText().compareTo(ID) == 0)
{
JOptionPane.showMessageDialog(null,rs1.getString("Full_Name") +
" is available","Query result",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
if(UIorBItf.getText().compareTo(ID) != 0)
{
JOptionPane.showMessageDialog(null, UIorBItf.getText() +" is
not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
}
if(RB2.isSelected()==true)
{
//JOptionPane.showMessageDialog(null, UIorBItf.getText() +" Now
//You are inside Book search","Query result",JOptionPane.INFORMATION_MESSAGE);
Statement stmt2= (Statement)conn.createStatement();
String SQL2 = "select * from books";
ResultSet rs2 = stmt2.executeQuery(SQL2);
String ID ="";
while(rs2.next())
{
ID = rs2.getString("BookID");
if(ID.compareTo(UIorBItf.getText()) ==0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is available","Query result",JOptionPane.INFORMATION_MESSAGE);
break;
}
}
if(UIorBItf.getText().compareTo(ID)!=0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
}
}catch(Exception e)
{
System.out.println("Error: " + e.getMessage());
}
if(UIorBItf.getText().compareTo(ID)!=0)
{
// problem is here
// from other code I am guessing you want UIorBItf.getText()
// instead of rs2.getString("Book_Name")
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
The problem is here:
if(UIorBItf.getText().compareTo(ID)!=0)
{
JOptionPane.showMessageDialog(null,rs2.getString("Book_Name") +
" is not available","Query result",JOptionPane.INFORMATION_MESSAGE);
}
You can't call rs2.getString("Book_Name") from here, since you only end up here when the while loop is finished. At this point you will already have moved past the last line since rs2.next() has returned false.
You cannot call
rs2.getString("Book_Name")
if rs2.next()
doesnt match anything from your query
select * from books
I have been creating a program that is to add search delete bookings etc...
After hours I finally thought I was making progress but when I delete a booking my program finds the correct booking returns the correct information for that booking but deletes a different booking.
I have attached the files in a zip as if I displayed them they would take up lots of screen space. The program has been made in BlueJay.
Code for decleration and adding of objects into my array list
public Hostel(String hostelName)
{
this.hostelName = "Newcastle Hostel";
bookings = new ArrayList<Booking>();
}
public String getHostelName()
{
return hostelName;
}
public String addBooking(String roomID, String roomType, String guest)
{
if (roomID.equals(""))
return "Error Please Entre Room ID";
else if (roomType.equals(""))
return "Error Please Entre Room Type";
else if (guest.equals(""))
return "Error Please Entre Guest Name";
bookings.add(new Booking(roomID,roomType,guest));
return "Room " + roomID + " " + roomType + " Has Been Booked For " + guest;
}
This is taken from my hostel class
public String deleteBooking(String roomID)
{
int index = 0;
for ( Booking s : bookings )
{
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
bookings.remove(index);
}
index++;
}
}
return " Cannot find room";
}
this is taken from my GUI class
else if (item.equals("Cancel Booking"))
{
newBookingButton.setEnabled(false);
cancelBookingButton.setEnabled(false);
String roomID = JOptionPane.showInputDialog(this, "Enter a room ID", "Delete a Booking", JOptionPane.QUESTION_MESSAGE);
output.setText(hostel.deleteBooking(roomID));
newBookingButton.setEnabled(true);
cancelBookingButton.setEnabled(true);
}
Any additonal code needed either ask or there is a full copy in the link above thanks
Your loop only increments the index if the room ID of the current room is equal to the ID of the room to delete. The line
index++;
should be out of the if block.
EDIT:
The other problem is that you're trying to remove elements a collection while iterating on it. This is only possible if you use an Iterator to iterate over the collection, and use the iterator's remove method to remove the current element. Note that even if it was possible, since you remove the element at the given index, the index should not be incremented since you have just removed the element at this index.
Example of using an iterator:
for (Iterator<Booking> it = bookings.iterator(); it.hasNext(); ) {
Booking b = it.next();
if (...) {
it.remove();
}
}
Basically when s.getRoomID().equals(roomID) is true your if block is executed so no matter what is the response of the user your index is incremented. So, do this:
if ( s.getRoomID().equals(roomID))
{
//your code
}
index++
I just looked into your code, and seems like you are trying to iterate over a collection and also modifying the values at the same time. With enhanced for loop, such things do give errors, so instead of using the enhanced for loop, you must use a normal for loop. So I had modified your deleteBookings Method for the respective change.
public String deleteBooking(String roomID)
{
//for ( Booking s : bookings )
for (int i = 0; i < bookings.size(); i++)
{
Booking s = bookings.get(i);
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
//int r = JOptionPane.showOptionDialog,null("Are you sure you would like to delete the following \n"
//+ "deleteMessage",
//"Delete a booking",
//JOptionPane.YES_NO_OPTION,
//JOptionPane.QUESTION_MESSAGE,null,null,null);
//if (r == JOptionPane.YES_OPTION) {
// bookings.remove(index);
//}
//if (r == JOptionPane.NO_OPTION){
// return "Booking Was Not Canceled";
// }
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
//bookings.remove(index);
bookings.remove(i);
return deleteMessage + " has been DELETED."; /*I did this.*/
}
}
}
return " Cannot find room";
}
Moreover, after this
bookings.remove(i);
You forgot to return something like
return deleteMessage + " has been DELETED."; /*I did this.*/
Since you failed to return a String on successful completion, that's the reason why it returns "Cannot find room.", even after successful deletion.
Rest of the code is perfect.
Hope that might solve your query.
Regards