Accessing database information inside a loop and storing outside - java

The issue is definitely within the scope but, I am having issues figuring out why since I declared the variables that are storing the information outside the loop
public Member searchMember (String email) {
int Sid = 0;
String name ="";
String adr = "";
String phone = "";
String email2 = "";
String pass = "";
boolean status =false;
Member a = new Member(name,adr,phone,email2,pass);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://compsi:3306/mcrowley","mcrowley","700463874");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
System.out.println(email);
String query = "Select id,name,address,phoneNum,email,password,LoginStatus From member WHERE email Like '%"+email+"%' ";
ResultSet results = stmt.executeQuery(query);
System.out.println("Before while loop");
int count = 0;
while (results.next() || count == 0 ) {
if (count == 0)
results.absolute(1);
System.out.println("Start while loop");
Sid = results.getInt(1);
//System.out.println(Sid+" this is test in jdbc");
name = results.getString(2);
//System.out.println(name+" this is test in jdbc");
adr = results.getString("address");
phone = results.getString("phoneNum");
email2 = results.getString("email");
pass = results.getString("password");
int stat = results.getInt("loginStatus");
if (stat == 0) {
status = false;
}
else {
status = true;
}
count++;
if (!results.next()) {
a.setName(name);
a.setAddress(adr);
a.setPhoneNumber(phone);
a.setEmail(email2);
a.setPassword(pass);
a.setId(Sid);
a.setStatus(status);
return a;
}
}
System.out.println("After while loop");
a.setName(name);
a.setAddress(adr);
a.setPhoneNumber(phone);
a.setEmail(email2);
a.setPassword(pass);
a.setId(Sid);
a.setStatus(status);
//create object & print
stmt.close();
con.close();
return a;
}
catch (Exception e) {
e.printStackTrace();
}
return a;
}

So basically it sounds like you need a refresher course about the scope of variables.
Essentially, you're not coming here with broken code that you want to know how to fix. But instead you're being rolling because you think it ought not to work.
Here's how I remember it: every scope has access to variables declared in itself as well as the scope that is its direct parent. That is, the parent scope can't read and modify any of its soon-to-be cheers.
So basically, the answer to your question is that your intuition is incorrect. Variable scope doesn't function in the way you thought it did.

Related

Efficiently Looping through Object array with Multiple Variable types in Java

I'm writing a simple script in Java that is calling another class that holds all my information.
I am holding my information in the called class in Object[] Arrays and I am planning on calling the script to fetch that array.
Right now the function looks like this.
public void tradeShop() {
/*
*Variables must be initialized in order to call shopTrader
*The values are just non-null placeholders and they are
*replaced with the same values in the tradeValues Object array.
*/
String targetName = "NPC Name";
String itemName = "Item Name";
int itemQuantity = 1;
int minCoins = 1;
int minBuy = 1;
boolean stackable = false;
Object[] tradeValues = shop.defaultValues;
for (int i = 0; i < tradeValues.length; i++) {
if(String.class.isInstance(tradeValues[i])) {//String check
if(i==0) { //0 is NPC Name
targetName = (String) tradeValues[i];
} else if (i==1) { //1 is Item Name
itemName = (String) tradeValues[i];
}
} else if (Integer.class.isInstance(tradeValues[i])) { //Int check
if(i==2) { //2 is Item Quantity
itemQuantity = (Integer) tradeValues[i];
} else if (i==3) { //3 is Minimum coins
minCoins = (Integer) tradeValues[i];
} else if (i==4) { //4 is the Minimum Buy limit
minBuy = (Integer) tradeValues[i];
}
} else if (Boolean.class.isInstance(tradeValues[i])) { //Bool check
stackable = (Boolean) tradeValues[i]; //5 is the item Stackable
} else {
//TODO: Implement exception
}
}
//Calls ShopTrader() method shopTrader
ShopTrader trade = new ShopTrader();
trade.shopTrader(targetName, itemName, itemQuantity, minCoins, minBuy, worldHop, stackable);
}
I feel like using a for loop like this is not the correct way for me to be looping through these Objects, I shouldn't have to check i== for each variable.
Also it hinders me from adding overloads to the shopTrader method as I would have to write an entirely new for loop for each overload.
Does anyone have a more elegant solution for getting the variables from this array?
I think that instead of storing all of your information in Object[], you may want to create a new class to act as a data structure i.e.
public class TradeValue {
String targetName;
int itemQuantity;
// etc.
String getTargetName() {
return targetName;
}
String getItemQuantity() {
return itemQuantity;
}
// etc
}
You can then just access the information directly
TradeValue defaultValues = shop.defaultValues;
String targetName = defaultValues.getTargetName();
int itemQuantity = defaultValues. getItemQuantity();
...

Exhausted Resultset when calling a method inside the while(rset.next)

I'm getting an Exhausted resultset form the following code.
I've tried a few different things now and can't find a solution,
if I don't call the songs method it works, but the songs method works when it's called, can't get my head around it, hoping I'm missing something simple.
public void refreshList() {
rset = po.getProduct();
if (plist.size() > 0) {
for (int i = plist.size() - 1; i >= 0; i--) {
plist.remove(i);
}
}
try {
while (rset.next()) {
songs(rset.getString(1));
CD c = new CD(alist);
Product p = new Product(rset.getString(1),
rset.getString(2),
rset.getString(3),
rset.getDouble(4),
rset.getDouble(5),
rset.getInt(6),
rset.getString(7),
rset.getString(8),
rset.getString(9),
rset.getDouble(10), c);
plist.add(p);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
public void songs(String ID)
{
rset = po.getSongs();
alist = new ArrayList<Song>();
try {
while (rset.next()){
Song s = new Song(rset.getString(1),
rset.getString(2),
rset.getString(3));
slist.add(s);
}
}
catch (Exception ea) {
System.out.println(ea);
}
for(int i = 0; i < slist.size(); i++)
{
if(slist.get(i).getSong_id().equals(ID))
{
alist.add(slist.get(i));
}
}
}
Inside refreshList you have while (rset.next()) loop, on each iteration of it you have songs(rset.getString(1));, which itself has while(rset.next(). This leads to result set exhaustion, because when you return from songs() you try to take some more data from the current position of result set, while in songs() you got out of while (rset.next()) loop, i.e. retrieved all its rows. Consider refactoring your code to avoid nested loops based on result set.

Java - object existence dilem

I wrote the following, this is a toString of a Country class that has City class in same package, and _cities is an array represents the cities within my Country:
**EDITED:**
public String toString(){
String allCitiesData = ""; //must be initialized
for(int i=0;this._cities[i] != null;i++)//run all over the cities until reach the end(null cell)
{ //concat new city to the string and adds a new line between
allCitiesData = allCitiesData.concat(this._cities[i].toString()+"\n\n");
}
return allCitiesData;
}//toString method
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
Point referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}//citiesNorthOf method
But, when I run it, it shows a single error only on this line:
if (this._cities[i].getCityCenter().isAbove(referenceCityCenter))
And the Eclipse says: "referenceCityCenter cannot be resolved to a variable".. any suggestions ?
Thanks !!
You have declared referenceCityCenter in a scope which is not visible to that line of your code. Try declaring it at the beginning of the method (and control too if it is null when it arrives to your validation .isAbove()! :P )
referenceCityCenter is out of scope. Put it outside of your if statement and make sure you check for null afterwards like follows:
public String citiesNorthOf(String cityName){
String allCitiesNorthOf = "";// must be initialized
Point referenceCityCenter = null;
for(int i=0; this._cities[i] != null ; i++)
{
if (this._cities[i].getCityName() == cityName)
{
referenceCityCenter = new Point(this._cities[i].getCityCenter());
}
}
for(int i=0; this._cities[i] != null ; i++)//we don't need to exclude the comparable city itself because it will give a false
{
if (referenceCityCenter !- null && this._cities[i].getCityCenter().isAbove(referenceCityCenter))
{
allCitiesNorthOf = allCitiesNorthOf.concat(this._cities[i].toString()+"\n\n");
}
}
}

I am getting en error for the misplaced return statement while retriving the values for a particular ssnum from the mysql database

public Customer getCustomer(String ssNum) throws CustomerHomeException, ClassNotFoundException {
String query = "Select ssn, customer_name from customer ";
ResultSet rs = smt.executeQuery(query);
Customer customer = null;
while (rs.next()) {
if (ssNum.equals(rs.getString("ssn"))) {
customer = new Customer(rs.getString("ssn"), rs.getString("customer_name"));
}
return customer;
}
} catch (SQLException e) {
throw new CustomerHomeException("Failed to create CustomerHome", e);
}
}
I'm getting an error for the return statement placed while retriving the value from the MySQL database. Value already exists.
Method getCustomer expecting to return customer at the end of function definition. and you are returning in the middle of while loop. So Compiler complaining to add or place return statement as your method suppose to, because its not always happening that while or if will get executed every time.
private static int hello() {
for (int i = 0; i < 2; i++) {
return 0;
}
return -1;
}
I hope this helps.

Child Class Attribute error

I have a child (extended) class with a protected attribute height.
I want to access it in the main program:
while(line != null)
{
String[] field = line.split("#");
int height = Integer.parseInt(field[0]);
if (field.length ==1)
{
forest[cnt] = new Trees(height);
}
else
{
forest[cnt] = new Shrub(height, field[1]);
}
cnt++;
line = inS.readLine();
}
inS.close();
String s = JOptionPane.showInputDialog("Enter Name to search for");
for(int i = 0; i<forest.length; i++)
{
if (forest[i] instanceof Shrub)
{
String a = forest[i].getName();
System.out.println ("Found");
}
}
}
However I get an error saying that it cannot find the method getName, however when i run the lol Shrub it works fine?
Thanks.
Private access modifier methods are not accessible in child class. Make them Public or Protected.

Categories