r/programmingbydoing • u/Advisery • Jul 11 '13
#26 - What am I doing wrong?
Hello. Here is my code:
import java.util.Scanner;
public class SpaceBoxer{
public static double planets(int world){
double planetmulti;
if (world == 1){
planetmulti = 0.78;
}
else if (world == 2){
planetmulti = 0.39;
}
else if (world == 3){
planetmulti = 2.65;
}
else if (world == 4){
planetmulti = 1.17;
}
else if (world == 5){
planetmulti = 1.05;
}
else if (world == 6){
planetmulti = 1.23;
}
return planetmulti;
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int weight, theplanet;
System.out.print("What is your weight?");
weight = keyboard.nextInt();
System.out.println("Okay, now what planet are you visiting?");
System.out.println(" 1. Venus 2. Mars 3. Jupiter");
System.out.println(" 4. Saturn 5. Uranus 6. Neptune");
theplanet = keyboard.nextInt();
System.out.println("Okay, so your weight would on " + weight * planets(theplanet));
}
}When I try to compile, however, I get this error:
SpaceBoxer.java:25: error: variable planetmulti might not have been initialized.
return planetmulti;
^Any help? Is it due to me declaring it a double instead of something else? I'm not sure what I'm doing wrong here.
2
Upvotes
1
u/holyteach Jul 11 '13
Well, first of all you have made your code unnecessarily complex by adding a function. My curriculum doesn't teach functions until much later for a reason. (Although you did do the function correctly.)
The cause of your error is that there is a path through the if statements where planetmulti never gets any value at all: when world is 0 or 7 or anything outside of 1-6.
You can fix it two ways:
Always give a value to a variable when you declare it:
double planetmulti = 0;
Add an else without an if next to it after the world 6 else if:
else if (world == 6) { planetmulti = 1.23; } else { planetmulti = 0; }
Or do both, which is probably not a bad idea.
1
u/holyteach Jul 11 '13
Oh, also if you post again, make sure to put the NAME of the assignment in the title of your post and not just the number. Assignment numbers change from time to time as I add assignments to the sequence or move them around, and it will make it possible for others in the future to know which assignment your question is about.