Whenever I get to the part of saving the table- it asks me for the ID number but then it comes up with the following error:
"Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: ResultSet closed"
I can't figure out what the problem is.
Should I use the same ResultSet variable name for all functions?
public class Events {
public static void ambush(int mymovement) {
try {
Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
Statement statement = conn.createStatement();
System.out.println("You have been ambushed" + "\n" +
" You have moved 1 mile" + "\n"
+ "Your health, ammunition and supplies have reduced by 40%.");
System.out.println("Enter your ID to save your progress: ");
Scanner id = new Scanner(System.in);
int myid = id.nextInt();
ResultSet ambush = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
+ " WHERE " + DatabaseConstants.Column_ID + " = " + myid);
while (ambush.next()) {
statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
DatabaseConstants.Column_Health + " = " + (ambush.getInt(DatabaseConstants.Column_Health) - 40) + ", " +
DatabaseConstants.Column_Supplies + " = " + (ambush.getInt(DatabaseConstants.Column_Supplies) - 40) + ", " +
DatabaseConstants.Column_Ammo + " = " + (ambush.getInt(DatabaseConstants.Column_Ammo)- 40) + ", " +
DatabaseConstants.Column_Location + " = " + (ambush.getInt(DatabaseConstants.Column_Location) + mymovement) +
" WHERE " + DatabaseConstants.Column_ID + " = " + myid);
if (mymovement == 10) {
System.out.println("You have moved 10 miles - you have completed the mission");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (ambush.getInt(DatabaseConstants.Column_Health) == 0) {
System.out.println("Your health is 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (ambush.getInt(DatabaseConstants.Column_Supplies) == 0) {
System.out.println("Your supplies are 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (ambush.getInt(DatabaseConstants.Column_Ammo) == 0) {
System.out.println("Your ammunition is at 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (mymovement < 10) {
System.out.println("Your progress has been saved - You will be re-directed to the main menu");
DatabaseConstants.showMenu();
}
}
ambush.close();
statement.close();
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void fire(int mymovement) {
try {
Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
Statement statement = conn.createStatement();
System.out.println("Your journey has been affected by fire" + "\n" +
" You have moved 2 miles" + "\n"
+ "Your health and supplies have reduced by 30%. Your ammunition has stayed the same");
System.out.println("Enter your ID to save your progress: ");
Scanner id = new Scanner(System.in);
int myid = id.nextInt();
ResultSet fire = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
+ " WHERE " + DatabaseConstants.Column_ID + " = " + myid);
while (fire.next()) {
statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
DatabaseConstants.Column_Health + " = " + (fire.getInt(DatabaseConstants.Column_Health) - 30) + ", " +
DatabaseConstants.Column_Supplies + " = " + (fire.getInt(DatabaseConstants.Column_Supplies) - 30) + ", " +
DatabaseConstants.Column_Ammo + " = " + (fire.getInt(DatabaseConstants.Column_Ammo)) + ", " +
DatabaseConstants.Column_Location + " = " + (fire.getInt(DatabaseConstants.Column_Location) + mymovement) +
" WHERE " + DatabaseConstants.Column_ID + " = " + myid);
if (mymovement == 10) {
System.out.println("You have completed the mission");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (fire.getInt(DatabaseConstants.Column_Health) == 0) {
System.out.println("Your health is 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (fire.getInt(DatabaseConstants.Column_Supplies) == 0) {
System.out.println("Your supplies are 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (fire.getInt(DatabaseConstants.Column_Ammo) == 0) {
System.out.println("Your ammunition is at 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (mymovement < 10) {
System.out.println("Your progress has been saved - You will be re-directed to the main menu");
DatabaseConstants.showMenu();
}
}
fire.close();
statement.close();
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void badweather(int mymovement) {
try {
Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
Statement statement = conn.createStatement();
System.out.println("You journey has been affected by bad weather" + "\n" +
" You have moved 3 mile" + "\n"
+ "Your health and supplies have reduced by 20%.");
System.out.println("Enter your ID to save your progress: ");
Scanner id = new Scanner(System.in);
int myid = id.nextInt();
ResultSet badweather = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
+ " WHERE " + DatabaseConstants.Column_ID + " = " + myid);
while (badweather.next()) {
statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
DatabaseConstants.Column_Health + " = " + (badweather.getInt(DatabaseConstants.Column_Health) - 20) + ", " +
DatabaseConstants.Column_Supplies + " = " + (badweather.getInt(DatabaseConstants.Column_Supplies) - 20) + ", " +
DatabaseConstants.Column_Ammo + " = " + (badweather.getInt(DatabaseConstants.Column_Ammo) - 20) + ", " +
DatabaseConstants.Column_Location + " = " + (badweather.getInt(DatabaseConstants.Column_Location) + mymovement) +
" WHERE " + DatabaseConstants.Column_ID + " = " + myid);
if (mymovement == 10) {
System.out.println("You have moved 10 miles - you have completed the mission");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (badweather.getInt(DatabaseConstants.Column_Health) == 0) {
System.out.println("Your health is 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (badweather.getInt(DatabaseConstants.Column_Supplies) == 0) {
System.out.println("Your supplies are 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (badweather.getInt(DatabaseConstants.Column_Ammo) == 0) {
System.out.println("Your ammunition is at 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (mymovement < 10) {
System.out.println("Your progress has been saved - You will be re-directed to the main menu");
DatabaseConstants.showMenu();
}
}
badweather.close();
statement.close();
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void noEvent (int mymovement) {
try {
Connection conn = DriverManager.getConnection(DatabaseConstants.Database);
Statement statement = conn.createStatement();
System.out.println("Your journey has not been affected by any adverse event" + "\n" +
" You have moved 4 mile2" + "\n"
+ "Your health and supplies have reduced by 10%.");
System.out.println("Enter your ID to save your progress: ");
Scanner id = new Scanner(System.in);
int myid = id.nextInt();
ResultSet noEvent = statement.executeQuery("SELECT * FROM " + DatabaseConstants.Table_Troops
+ " WHERE " + DatabaseConstants.Column_ID + " = " + myid);
while (noEvent.next()) {
statement.execute("UPDATE " + DatabaseConstants.Table_Troops + " SET " +
DatabaseConstants.Column_Health + " = " + (noEvent.getInt(DatabaseConstants.Column_Health) - 10) + ", " +
DatabaseConstants.Column_Supplies + " = " + (noEvent.getInt(DatabaseConstants.Column_Supplies) - 10) + ", " +
DatabaseConstants.Column_Ammo + " = " + (noEvent.getInt(DatabaseConstants.Column_Ammo) - 10) + ", " +
DatabaseConstants.Column_Location + " = " + (noEvent.getInt(DatabaseConstants.Column_Location) + mymovement) +
" WHERE " + DatabaseConstants.Column_ID + " = " + myid);
if (mymovement == 10) {
System.out.println("You have moved 10 miles - you have completed the mission");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (noEvent.getInt(DatabaseConstants.Column_Health) == 0) {
System.out.println("Your health is 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (noEvent.getInt(DatabaseConstants.Column_Supplies) == 0) {
System.out.println("Your supplies are 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (noEvent.getInt(DatabaseConstants.Column_Ammo) == 0) {
System.out.println("Your ammunition is at 0%");
System.out.println("Your session will now be terminated");
System.exit(0);
} else if (mymovement < 10) {
System.out.println("Your progress has been saved - You will be re-directed to the main menu");
DatabaseConstants.showMenu();
}
}
noEvent.close();
statement.close();
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
The code is interleaving the ResultSet and Statement instances.
Please refer to:
java.sql.Statement API:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a current ResultSet object of the statement if an open one exists.
I've been trying to make this work, but it keeps getting stuck. The part with withdraw works perfectly but for create it freezes.
tellerReady, queueNotempty, createcomplete, withdrawcomplete and others like that are semaphores. There are several classes which work fine, but the parts you see below are causing problem:
//withdrawal being made
if (task == 2) {
mutex.acquire();
bankTellQueue.add(num);
queueNotEmpty.release();
mutex.release();
tellerReady[num].acquire();
withdraw[num] = 100 * (1 + (int) (Math.random() * 5));
System.out.println("Customer " + num + " requests from the teller " + servingTeller[num] + " to make a withdrawal of $" + withdraw[num]);
Thread.sleep(100);
banktellerRequest[servingTeller[num]].release();
withdrawalReceipt[servingTeller[num]].acquire();
Thread.sleep(100);
System.out.println("Customer " + num + " gets their cash and receipt from the teller " + servingTeller[num]);
withdrawalComplete[servingTeller[num]].release();
}
if (task == 3) {
mutex1.acquire();
bankTellQueue.add(num);
queue1NotEmpty.release();
mutex1.release();
tellerReady[num].acquire();
Create[num] = num;
System.out.println("Customer " +num + " Creates account");
Thread.sleep(100);
banktellerRequest[servingTeller[num]].release();
createComplete[servingTeller[num]].acquire();
Thread.sleep(100);
System.out.println("Account created by teller " +servingTeller[num]);
createComplete[servingTeller[num]].release();
}
Also there is this part in the class of Teller:
if (nextcustomertask == 2) {
Customer.banktellerRequest[num].acquire();
System.out.println("Teller " + num + " processes withdrawal for Customer " + nextcustomer);
Thread.sleep(300);
Customer.customerBalance[nextcustomer] = Customer.customerBalance[nextcustomer] - Customer.withdraw[nextcustomer];
Customer.withdrawalReceipt[num].release();
Customer.withdrawalComplete[num].acquire();
}
//handling create account
if(nextcustomertask ==3 ) {
Customer.banktellerRequest[num].acquire();
System.out.println("Teller " + num + " processes Create account for customer " + nextcustomer);
Thread.sleep(300);
Customer.customerBalance[nextcustomer] = 1000;
Customer.createReceipt[num].release();
Customer.createComplete[num].acquire();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
UPDATE: I found where the problem was. I was using the wrong semaphore.
I wrote a program that asks for user input (numbers), then tells the user which of the two numbers they put in are bigger after making sure both values are numbers. This is looped. The problem is, when the user enters something that isn't valid, the program shuts down instead of referring to my else statements. I think this is because text values in strings cannot be processed using parseInt() so instead of the program realizing that a text value isn't a valid number, it just fails. I am using BlueJ to make this program if that helps anyone solve the problem. I am also open to people telling me how to make my program more efficient/easier to code (I am a beginner).
import java.util.Scanner;
public class TemperatureDriver {
public static void main(String[] args) {
while (true) {
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter a number"+ "\n");
String number_one = keyInput.next();
if (Integer.parseInt(number_one) <=0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if(Integer.parseInt(number_two) <=0 || Integer.parseInt(number_two) > 0){
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) < Integer.parseInt(number_two)){
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) == Integer.parseInt(number_two)){
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
}
}
}
Your code where you call parseInt should be embedded in a try block, which should be followed by a catch block to catch the NumberFormatException.
try {
if (Integer.parseInt(number_one) <= 0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if (Integer.parseInt(number_two) <= 0 || Integer.parseInt(number_two) > 0) {
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) < Integer.parseInt(number_two)) {
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) == Integer.parseInt(number_two)) {
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}
I am trying to do this project and for some reason I am having an issue that for the life of me I can not solve.
public static void printlist(String n){
for(int i=0; i< roomlist.size(); i++){
if(roomlist.get(i).name.equals(n)){
System.out.println("Room Name: " + roomlist.get(i).name + " state: " + roomlist.get(i).state);
System.out.println("Description: " + roomlist.get(i).desc);
System.out.println("Creatures in Room: " + roomlist.get(i).Fred());
if(roomlist.get(i).north != null){
System.out.println("North Neighbor: " + roomlist.get(i).north.name);
}
if (roomlist.get(i).south !=null){
System.out.println("South Neighbor: " + roomlist.get(i).south.name);
}
if (roomlist.get(i).east !=null){
System.out.println("East Neighbor: " + roomlist.get(i).east.name);
}
if (roomlist.get(i).west !=null){
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
}
}
System.out.println("Room " + n + " does not exist!");
}
Right now even if it finds the Room object in the ArrayList it still prints "Room " + n + " does not exist!" I need it to only print that if the room is not found in the ArrayList
The reason it happens is because the Not found message is the last statement of your method. You should instead return from the method as soon as you found your element and you printed your wanted messages.
For example assuming each room has a unique name:
...
if (roomlist.get(i).name.equals(n)) {
...
if (roomlist.get(i).west != null) {
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
return;
}
...
Basically, System.out.println("Room " + n + " does not exist!"); will always be executed, because there is nothing stopping it
Assuming that there can be more then one neighboring room, it might be easier to use a simple flag to indicate if any rooms where found
public static void printlist(String n){
boolean foundRoom = false;
for(int i=0; i< roomlist.size(); i++){
if(roomlist.get(i).name.equals(n)){
foundRoom = true;
System.out.println("Room Name: " + roomlist.get(i).name + " state: " + roomlist.get(i).state);
System.out.println("Description: " + roomlist.get(i).desc);
System.out.println("Creatures in Room: " + roomlist.get(i).Fred());
if(roomlist.get(i).north != null){
System.out.println("North Neighbor: " + roomlist.get(i).north.name);
}
if (roomlist.get(i).south !=null){
System.out.println("South Neighbor: " + roomlist.get(i).south.name);
}
if (roomlist.get(i).east !=null){
System.out.println("East Neighbor: " + roomlist.get(i).east.name);
}
if (roomlist.get(i).west !=null){
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
}
}
if (!foundRoom) {
System.out.println("Room " + n + " does not exist!");
}
}
You could probably optimise it by using a List of some kind to store the neighboring rooms in and checking the size at the end, but the basic idea remains the same...
I have a java web application that I removed a function from the code and yet the database entries that this function writes are still being written to the database.
Inside the IssueWarrant function there is a call to insertWarrantFee that has been commented out.
private void issueWarrant(String CasePrefix, String CaseNumber, String HearingType, String Suspend)
{
int i = 0, intDivision = 0, pos = 0;
String SummSeq = getSummSeq(CasePrefix, CaseNumber);
String Charges = getCharges(CasePrefix, CaseNumber, HearingType);
boolean isVacated = false, isHearingFound = false;
NextBWNumber warrNbr = new NextBWNumber();
String WarrantNumber = warrNbr.getNextBWNumber();
String warrStatus = warrNbr.getNextBWNStatus();
String HearingDesc = "", Division = "";
isVacated = getVacatedStatus(CasePrefix, CaseNumber, HearingType);
isHearingFound = getHearingStatus (CasePrefix, CaseNumber, HearingType);
HearingDesc = getFormatToday() + " " + getHearingDesc(HearingType);
if (HearingDesc.length() > 30)
{
HearingDesc = HearingDesc.substring(0,30);
}
Division = getHearingJudge(CasePrefix,CaseNumber,HearingType);
intDivision = Integer.parseInt(Division);
if (intDivision < 10)
{ Division = "0" + Division; }
Statement localstmt = null;
String localqueryString;
localqueryString = "INSERT INTO " + library7 + "CMPBWPND" +
" (CASPRE, CASNUM, DEFSEQ, CHGSEQ, SUMSEQ, STSCOD, STSDAT," +
" STATUT, CHGABV, BWNBR, JUDCOD, PRVFLG, CT2FLG, DIVISN, BNDAMT," +
" BTYPE, CMNT, CUSER, TUSER, LUPDAT, SCRDAT, STATSDAT, SUMCRDAT, LUPDATE )" +
" VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + Charges.substring(i, i + 1) +
", " + SummSeq + ", 9, " + getShortDate() + ", 'RCP 12-A TA', 'WARRANT', '" +
WarrantNumber + "', " + intDivision + ", 'N', 1, '" + Division + "', " +
BondAmt + ", '" + BondType + "', '" + HearingDesc + "', 'TAAD', 'TAAD', " +
getShortDate() + ", " + getShortDate() + ", " + getLongDate() + ", " + getLongDate() +
", " + getLongDate() + ")";
try
{
if (!isVacated && isHearingFound)
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
StatusMsg = "Client No Show-WI";
}
if (isVacated)
{
StatusMsg = "Client Vacated Case";
}
if (!isHearingFound)
{
StatusMsg = "Client Hearing Missing";
}
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in IssueWarrant");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
**//insertWarrantFee(CasePrefix, CaseNumber, SummSeq, WarrantNumber);**
updateHearingRecord(CasePrefix, CaseNumber, HearingType, Charges.substring(i, i + 1), Suspend);
for ( i = 1; i < Charges.length(); i++ )
{
insertBWPTFRecord(CasePrefix, CaseNumber, SummSeq, Charges.substring(i, i + 1));
}
if (!success)
{
StatusMsg = "Client Iss. Warrant Failure";
}
}
Here is the code that the insertWarrantFee called before it was commented out:
private void insertWarrantFee(String CasePrefix, String CaseNumber, String SummSeq, String WarrantNumber)
{
Statement localstmt = null;
String localqueryString;
ResultSet localrSet = null;
String feeAmt = null;
localqueryString = "SELECT AUTO$$ FROM " + library3 + "CMPDKTTP WHERE DKTTYP = 'W'";
try
{
localstmt = conn.createStatement();
localrSet = localstmt.executeQuery(localqueryString);
while (localrSet.next())
{
feeAmt = localrSet.getString("AUTO$$");
}
localstmt.close();
localrSet.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Error in Insert Warrant Fee SQL1");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
localqueryString = "INSERT INTO " + library7 + "CMPBWTRN"
+ " (CASPRE, CASNUM, DEFSEQ, SUMSEQ, BWNBR, FEEAMT, DKTTYP, TUSER, LUPDAT)"
+ " VALUES ('" + CasePrefix + "', " + CaseNumber + ", 1, " + SummSeq + ", '" + WarrantNumber
+ "', " + feeAmt + ", 'W', 'TAAD', " + getShortDate() + ")";
try
{
localstmt = conn.createStatement();
localstmt.executeUpdate(localqueryString);
localstmt.close();
} catch (SQLException e)
{
System.out.println("IssueWarr - Insert Warrant Fee SQL2");
e.printStackTrace();
ReturnInfo = "Issuing Warrants Failed.";
success = false;
}finally
{
try
{
if (!localstmt.isClosed())
{
localstmt.close();
}
} catch (SQLException sql2)
{
System.out.println("Error trying to close connections. Exception: " + sql2.getMessage());
}
}
}
So even though the line that called insertWarrantFee is commented out a record is still being inserted into CMPBWTRN.
Any ideas how this could happen? The developer is indicating it could be a tomcat connection cache issue? Any other suggestion beside magical code?
Thanks!
Leslie
A couple of things to try:
Make sure you've redeployed the application and have restarted Tomcat. Check the timestamp of the deployed class in question.
Clean Tomcat's tmp and work directories
Open the deployed Java class using a decompiler to see whether the removed code is still in there.
Add a logging (or System.out.println) statement to the method that's commented out, and to the method calling it. See whether one or both are printed after redeploying the changes.