I’m a student starting out on my first programming module. The textbook I’m working from is ‘Java for Everyone’, Cay Horstmann. I’m on chapter 2.4 – Constants. I have copied and checked (over 15 times!) the code directly from the book, however every time I compile it produces the compile error in is already defined in main(java.lang.String[]).
It highlights Scanner in = new Scanner(System.in); as being the problem. I have written another extremely simple program which also includes Scanner in = new Scanner(System.in); and I had exactly the same problem.
I have tried to find the solution, I’ve reinstalled both Java JDK and BlueJ (compiler), but nothing has worked. I have Googled the problem, but I’m unable to find anything which matches my problem. I am a Java virgin, so to be honest it’s pretty difficult to work out where I should be looking.
Any help would be greatly appreciated. I’m behind a couple of weeks already, and this is holding my progress up considerably.
Thanks, in advance, for any advice offered.
All the best,
Vicky
import java.util.Scanner;
public class Volume2
{
public static void main(String[] args)
{
final double BOTTLE_VOLUME = 2;
final double LITRES_PER_OUNCE = 0.0296;
final double CAN_VOLUME = 12 * LITRES_PER_OUNCE;
System.out.print("Please enter quantity of bottles: ");
Scanner in = new Scanner(System.in);
int bottles = in.nextInt();
double totalVolume = totalVolume * BOTTLE_VOLUME;
System.out.print("Please enter the number of cans: ");
**Scanner in = new Scanner(System.in);** // This is highlighted as being the problem
int cans = in.nextInt();
double additionalVolume = cans * CAN_VOLUME;
totalVolume = totalVolume + additionalVolume;
System.out.print("The total volume is: ");
System.out.println(totalVolume);
}
}
Error Message: in is already defined in main(java.lang.String[])
Have a look at that code segment. You are indeed trying to create two copies of
in, exactly as the error message suggests.In a normal situation where you wanted to reuse a variable, you would simply assign to it the second time, such as with:
But, in your case, this does not apply, you’ve simply declared the variable twice.
So, subscribing to the “create variables as late as you possibly can” philosophy, I would get rid of the first one, it’s not needed. You could get rid of the second but that afore-mentioned philosophy has served me well, ensuring that creation and use of objects are localised.