Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2005

Tip: Looking for answers? Try searching our database.

Problem with String Variable

Thread view: 
machoextreme - 04 Dec 2005 07:15 GMT
As you can probably guess by the title, I'm a newbie. I'm still hitting
brick walls on with really easy solutions. One of them is on the latest
excersices in my textbook. I've written and compiled my program, but I
get this error. Any help/advice would be greatly appreciated.
variable act may not have been initialized

import java.util.*;

public class activities
{
    public static void main(String[] args)
{
    String act;
    int temp;
    Scanner keyboard= new Scanner(System.in);
    System.out.println("In order to decide what is the best activity at
the present time, please enter the current temperature ");
    temp = keyboard.nextInt();

    if (temp > 85)
    act = "Swimming";
    else if ((temp > 70) && (temp <= 85))
        act = "Tennis";
    else if ((temp > 32) && (temp <= 70))
        act = "Golf";
    else if ((temp > 0) && (temp <= 32))
        act = "Skiing";
    else if (temp <=0 )
        act = "Dancing";
    System.out.println("The recommened activity for the current
temperature is " );
    System.out.println(act);
   
   
   
   
}
}
di.dongke@163.com - 04 Dec 2005 07:31 GMT
variable act can be initialized like this:
String act = null;
machoextreme - 04 Dec 2005 07:41 GMT
Thanks alot. As I said, so far for me it's usually something really
stupid. The program works perfectly now.
IchBin - 04 Dec 2005 07:41 GMT
> As you can probably guess by the title, I'm a newbie. I'm still hitting
> brick walls on with really easy solutions. One of them is on the latest
> excersices in my textbook. I've written and compiled my program, but I
> get this error. Any help/advice would be greatly appreciated.
> variable act may not have been initialized

[snip]

>     String act;
Could change this to
        String act="";
[snip]

Signature

Thanks in Advance...
IchBin, Pocono Lake, Pa, USA
http://weconsultants.servebeer.com/JHackerAppManager
__________________________________________________________________________

'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor,  Regular Guy (1952-)

Chris Smith - 04 Dec 2005 15:39 GMT
> variable act may not have been initialized

You've gotten a few responses that will work, but none that is a good
idea.  Both responses suggested initializing the variable to a nonsense
value, null or "", which the variable should never actually hold.  It's
not a good idea to get into the habit of initializing local variables to
nonsense values in Java.  By doing so, all you do is prevent the
compiler from telling you when you really do forget to initialize
something to a sensible value.

The problem is that you don't have a final else clause in your if/else
chain.  It turns out that you happen to cover all possibilities with if
statements, but that's rather fragile.  There are two choices you could
make:

(1) Remove the last if statement, and make dancing a default:

   if (temp > 85) act = "Swimming";
   else if ((temp > 70) && (temp <= 85)) act = "Tennis";
   else if ((temp > 32) && (temp <= 70)) act = "Golf";
   else if ((temp > 0) && (temp <= 32)) act = "Skiing";
   else act = "Dancing";

(2) Add an explicit else and throw an exception:

   if (temp > 85) act = "Swimming";
   else if ((temp > 70) && (temp <= 85)) act = "Tennis";
   else if ((temp > 32) && (temp <= 70)) act = "Golf";
   else if ((temp > 0) && (temp <= 32)) act = "Skiing";
   else if (temp <= 0) act = "Dancing";
   else throw new RuntimeException("Forgot to specify this acitivity");

If dancing is a sensible default, then (1) causes your application to
continue working even if you mess up a temperature range.  If not, then
(2) at least guarantees that your application fails reliably and
consistently when you've broken things.  In either case, you aren't
lying to the compiler.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

Thomas Hawtin - 04 Dec 2005 16:14 GMT
>                            I've written and compiled my program, but I
> get this error.

I would take a slightly different approach to the other responders to
this thread. I would move declarations down to where they are first
needed. There is a path, which with a bit of effort looks as if in
practice that it is not possible, where act isn't assignable. Putting an
assignment there would suppress the error.

>     String act;
>     int temp;

Remove these two lines.

>     Scanner keyboard= new Scanner(System.in);
>     System.out.println("In order to decide what is the best activity at
> the present time, please enter the current temperature ");
>     temp = keyboard.nextInt();

Make this
     int temp = keyboard.nextInt();

The variable name looks as if it is just saying "temporary". A better
name would be something like temperatureFahrenheit. Outside of the US
Celsius is more common. Kelvin is often used in science and engineering
areas. Also "action" is probably better than "act".

We will need to declare act here. If we declare it final, then we can be
sure that there will be exactly one assignment.

        final String act;

>     if (temp > 85)
>     act = "Swimming";
[quoted text clipped - 6 lines]
>     else if (temp <=0 )
>         act = "Dancing";

If we slide in a further else statement, we can ensure that act is
"definitely assigned". There is a whole chapter on definite assignment
in the Java Language Specification, which isn't quite as dull as it
sounds. Essentially a variable is definitely assigned if all execution
paths definitely assign it, but the compiler does not check for tautologies.

So:

       else {
           act = "Unknown";
       }

Alternatively we could indicate that reaching that point is an error, with:

       else {
           throw new Error(
               "Unexpected execution path (temp="+temp+")"
           );
       }

Rather than redundantly checking each range, a better way to state this
particular logic is with something like:

    String act =
        (temp <=  0) ? "Dancing" :
        (temp <= 32) ? "Skiing"  :
        (temp <= 70) ? "Golf"    :
        (temp <= 85) ? "Tennis"  :
                       "Swimming";

The parentheses aren't strictly speaking necessary but, as inequalities
are not common (unlike ==null) in this position, I feel it worthwhile.

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.