Regarding the “uninitialized variables”:
The simplest fix is to initialize the variables to some value of your choice, e.g.:
double price1 = 0.0;
double price2 = 0.0;
Though your code compiles just fine on my machine (java 1.8.0_91).
But be careful how the values are initialized/changed during program flow. E.g. and invalid input in one of the two switch
-statements would cause your program to spit out an incorrect value.
Instead use an approach that removes redundant variables. E.g.: why use multiple variables for summing up the total price? Simply reuse a single variable for all additions:
double price = baseunit; //we know for sure the user selected the base-unit
...
switch(total1){
case 1:
price += screen1;
break;
...
}
...
Don’t create variables for single-use values. Eliminate the usage of total1
and total2
:
double baseunit = 375.99;
double screen1 = 75.99;
double screen2 = 99.99;
double dvd = 65.99;
double printer = 125.0;
double price1;
double price2;
...
switch(keyboard.nextInt()){
...
}
...
Simply continuing a program, after the user entered an invalid input won’t produce any useful/correct value. Notify him about the fact that the value he entered was useless and afterwards either terminate or ask again:
switch(keyboard.nextInt()){
...
default:
System.out.println("Invalid input");
return; //invalid input was entered, program is terminated
}