0

I've been coding one of my final school projects related to a text file based on weddings. I am trying to code a method that will return a wedding object,

(NOTE: weeding object consists of a brideName, groomName, weddingDate, Venue, number of Guests).

In a normal method using Strings. For example, I would merely type

String temp = ""; 

run a loop to loop through my array. if statement

temp = temp + arr[loop].toString();

return temp;

But now dealing with a wedding object when I declare it:

Wedding temp; - (As i cant initialize it as there is no brideName etc.)
run loop
if statement
temp = temp + array[loop];

return temp; 

Here is where i get the error of temp may not have been initialized.

Could anyone help with a suggestion of how to fix this? Thank you so much Here is what the actual method looks like

 public Wedding getWeddingsOnDay(String date, String venue)
{
    Wedding temp;
    for (int loop = 0; loop < counter; loop++)
    {
        if (wedArr[loop].getWeddingDate().equals(date) && wedArr[loop].getVenue().equals(venue))
            temp = wedArr[loop];
        else
            temp = null;
    }
    return temp;
}
shaik moeed
  • 5,300
  • 1
  • 18
  • 54

2 Answers2

1

Rewrite the method this way.

public Wedding getWeddingAt(String date, String venue) {
    for (Wedding w : wedArr)
    {
        if (w.getWeddingDate().equals(date) &&
                w.getVenue().equals(venue)) {
            return w;
        }
    }
    return null;
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
0

Your code will say this obviously beacise it is possible that you code will not go into the if block and temp varialble remain unintilized . So , anyone using it need to check null value before using this temp variable .

There are several ways you can remove this error :

  1. Ignore this error. As this error will not stop running your code .

  2. you can use optional intead of returing null , after this your method will lokks like below method :

    public Optional<Wedding> getWeddingsOnDay(String date, String venue){
    
      Optional<Wedding> temp;
      for (int loop = 0; loop < counter; loop++) {
          if (wedArr[loop].getWeddingDate().equals(date) && wedArr[loop].getVenue().equals(venue)) { 
              temp = Optional.of(wedArr[loop]);}
     else{
              temp = Optional.empty(); 
      }
    }
      return temp;    
    }
    
  3. You need not to use temp at all just return wedArr[loop] or null

Sahil Aggarwal
  • 1,311
  • 1
  • 12
  • 29