Hey everybody,
Can you help me in debugging the java code below. Am getting 2 errors at lines
1.) if(flag != 0 && flag != 1){
2.) for(int i=0;i<tankCount;i++){
The program is given below:
import java.util.Scanner;
class MileageDriver {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tankCount=0,flag=1,gasoline,milesdriven;
double tanks_MilePerGasoline[] = new double[50];
double avgMilesPerGasoline=0.0;
while(flag == 1 ){
System.out.print("
Enter details of vehicle " + (tankCount+1) + "-->");
System.out.print("
Gasoline filled :");
gasoline = sc.nextInt();
System.out.print("Miles driven :");
milesdriven = sc.nextInt();
tanks_MilePerGasoline[tankCount] = (milesdriven*1.0)/gasoline;
++tankCount;
System.out.print("
Do u want to enter more tank details(0:Exit, 1:yes, Max tanks:50) :");
flag = sc.nextInt();
if(flag != 0 && flag != 1){
System.out.print("Invalid input by user.");
}
}
for(int i=0;i<tankCount;i++){
System.out.print("
Miles per gasoline of vehicle " + (i+1) + " is :" + tanks_MilePerGasoline[i]);
avgMilesPerGasoline += tanks_MilePerGasoline[i];
}
System.out.print("
Average Miles per gasoline of all vehicles is :" + avgMilesPerGasoline);
System.out.println();
}
}
Comments
* Here is the corrected code.
**/
import java.util.Scanner;
class MileageDriver {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tankCount=0,flag=1,gasoline,milesdriven;
double tanks_MilePerGasoline[] = new double[50];
double avgMilesPerGasoline=0.0;
while(flag == 1 ){
System.out.print("
Enter details of vehicle " + (tankCount+1) + "-->");
System.out.print("
Gasoline filled :");
gasoline = sc.nextInt();
System.out.print("Miles driven :");
milesdriven = sc.nextInt();
tanks_MilePerGasoline[tankCount] = (milesdriven*1.0)/gasoline;
++tankCount;
System.out.print("
Do u want to enter more tank details(0:Exit, 1:yes, Max tanks:50) :");
flag = sc.nextInt();
/**This is your original statement
if(flag != 0 && flag != 1){
System.out.print("Invalid input by user.");
}
}
*/
/** This is the corrected statement.
*
* It is better to use while loop in making an iterative input and with options on what you wanted the user to input.
**/
while( flag != 0 && flag != 1){
System.out.print("Invalid input by user.");
flag=sc.nextInt();
}
}
for(int i=0;i<tankCount;i++){
System.out.print("
Miles per gasoline of vehicle " + (i+1) + " is :" + tanks_MilePerGasoline[i]);
avgMilesPerGasoline += tanks_MilePerGasoline[i];
}
System.out.print("
Average Miles per gasoline of all vehicles is :" + avgMilesPerGasoline);
System.out.println();
}
}