mercredi 29 avril 2015

if, else if, else statements: Within the blocks of code

I am a beginner programmer, and am currently banging my head against the wall over this assignment. I have to create a program that 'simulates' the use of a car, so it goes: drive, park, and fill up. The first thing it does is ask for how many litres of gas your tank can hold, and how many litres is currently in the tank. Then, it asks the user if it wants to a) drive, b) fill up, or c)park. I need to grab a user input (which I already know how to do), and depending on whether the user enters a,b, or c, it goes to this certain block of code and runs it.

Here are the specific instructions on what a, b, and c have to do: a) Drive: 1. enter the amount of Km driven (user inputs this) 2. Output how many litres of gas were used, and the amount of gas remaining in the tank. (we assume the car uses an average of 0.1 L/Km)

b) Fill up 1. User must enter the number of litres they wish to add 2. Output number of litres in tank. (the user can't input more litres than the tank can hold)

c) Park 1. Output number of litres in tank, and total number of Km driven. 2. This exits the loop

Am I using the right kind of loop? How do I get the code to run an equation (look at the red underlined lines)? Please help me, I'm so lost.

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("How many litres of gas can your tank hold?");
    int litreCap = scan.nextInt();
    System.out.println("How much gas is currently in your tank?");
    int startingLitre = scan.nextInt();
    System.out.println("Ok! Do you want to \n a) Drive \n b) Fill up, or \n c) Park");
    String abc = scan.next();
    String a, b, c;
    a = String.valueOf(1); //Wasn't sure if the problem had to do with the fact
    b = String.valueOf(2); //That I hadn't identified a,b and c
    c = String.valueOf(3);
    double litresUsed, gasTotal;

    if (abc .equals(a)) { //this is the drive section
        System.out.println("Please enter the amount of Kilometers driven.");
        int KmCount = scan.nextInt();
        litresUsed = 0.1*KmCount;//underlined yellow
        startingLitre - litresUsed = gasTotal;//this is underlined red
      }
    else if (abc .equals(b)){ //this is the fill up section
        System.out.println("OK! Please enter how many litres you are going to add.");
        int litresAdded = scan.nextInt(); //this is underlined yellow
        litresUsed + litresAdded = gasTotal; //underlined red
    }
    else {
        //enter c) Park code here
    }
}

}

Aucun commentaire:

Enregistrer un commentaire