How can I fix this java?

onlinegamerunibro

I am working on this program with these instructions:

Bus Passengers: Write a program that is to be used to count how many passengers are travelling on buses that pass a particular bus stop in a given hour. It should use a while loop to repeatedly ask the user to give the number of passengers on the bus that just passed. It should stop when the special code X is entered as the number of passengers. It should then give the number of buses and the total number of passengers counted in that hour. For example, one run might be as follows.

How many passengers were on the bus? 2
How many passengers were on the bus? 5
How many passengers were on the bus? 10
How many passengers were on the bus? 3
How many passengers were on the bus? 12
How many passengers were on the bus? 1
How many passengers were on the bus? 0
How many passengers were on the bus? X

There were a total of 33 passengers on 7 buses.

I am trying to fix an error:

Preeti

Few points to note:-

  1. You don't need System.exit()
  2. In java variables are only accessible inside their scope i.e. the region they are created in.

I tried to rewrite code as following:-

import java.util.Scanner;

public class Bus {
    int busCount =0;
    int passengerCount =0;
    Scanner scanner= new Scanner(System.in);

    public static void main(String args[]){
        Bus bus = new Bus();
        bus.getResults();
    }

    private void addBusAndPassenger(String input){
        try{
            int a = Integer.parseInt(input);
            busCount = busCount + 1;
            passengerCount = passengerCount + a;
        }catch(NumberFormatException e){
            System.out.println("Please provide integer or X as input");
        }
    }

    private void getResults(){
        String a =null;
        while (!("X".equals(a))){
            System.out.print("How many passengers were on the bus? ");
            a = scanner.nextLine();
            if("X".equals(a))
                break;

            addBusAndPassenger(a);
        }
        System.out.println("There were a total of " + passengerCount + " passengers on " + busCount + " buses.");
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related