Initializing and Receiving Variables, Creating Methods
For an online class I'm taking, we are creating an interactive version of the "99 Bottles of Beer" song. The user is supposed to be able to enter a quantity, container, and substance, and then those are supposed to be used in creating the song, so that it displays from "3 bags of chips..." to "2 bags of chips...", etc. I've had a couple hiccups in terms of variables, as my Eclipse IDE insist they haven't been initialized... can anyone help me?
Oh yeah, code:
package lab07;
import java.util.Scanner;
public class ConsumptionSongConsoleDriver {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("\tquantity: ");
int quantity = keyboard.nextInt();
System.out.print("\tcontainer: ");
String container = keyboard.nextLine();
keyboard.nextLine();
System.out.print("\tsubstance: ");
String substance = keyboard.nextLine();
System.out.println(makeSong() );
}
public static String makeSong() {
int quantity;
String container, substance;
String result = "";
for(int count; quantity >= 0; quantity--) {
result = count + "" + container + "s of " + substance + "on the wall," + count + container + "s of " + substance + "." + "Take one down, pass it around." + (count - 1) + "" + container + "s " + "of " + substance + "on the wall.\n";
}
return result;
}
}
(Please, when giving solutions, keep it simple; the assignment is supposed to be this way, and we aren't that advanced yet.)
Re: Initializing and Receiving Variables, Creating Methods
Quote:
I've had a couple hiccups in terms of variables, as my Eclipse IDE insist they haven't been initialized.
With compiler messages its always a good idea to post the message exactly as you see it. And indicate which line of your code it is referring to.
-----
As far as the need to initialise variables is concerned, this is just common sense but it is something we are apt to miss as we struggle with trying to do something unfamiliar as writing code is to begin with.
"How long is a piece of string?"
The point is that we cannot answer this unless we know *which* piece of string is being talked about. Variables and expressions like "a piece of string" have to have actual values before we can ask meaningful questions about them or do anything else with them. With variables it means they have to be given a value (be initialised) before you can do anything with them.
Read through your code (or be guided by the compiler messages) and try to find the places where you try to use a variable, but have not yet given it a value. One thing to bear in mind is that variables declared in different methods have nothing to do with one another: they are different variables. This is true generally of variables declared in different {...} blocks.
Re: Initializing and Receiving Variables, Creating Methods
In your for loop, "count" & "quantity" is not initialized.