如何修复这个java?

nc1teljy  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(255)

我正在按照以下说明编写此程序:
公共汽车乘客:编写一个程序,用来计算在给定的时间内经过某个公共汽车站的公共汽车上有多少乘客。它应该使用while循环来反复要求用户给出刚刚经过的公交车上的乘客人数。当输入特殊代码x作为乘客人数时,应停止。然后它应该给出公车的数量和在这一小时内统计的乘客总数。例如,一次运行可能如下所示。

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.

我正在尝试修复一个错误:

f5emj3cl

f5emj3cl1#

有几点需要注意note:-
您不需要system.exit()
在java中,变量只能在其作用域内访问,即在其中创建变量的区域。
我试着重写代码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.");
    }
}
ebdffaop

ebdffaop2#

这里有几件事。其他人指出了这一点,但您需要将参数传递给您的方法。方法签名的存在是有原因的-您的方法调用必须与您定义的方法签名匹配。
也, busInformation 应该返回一个 int ,但它什么也不返回。
此外,这一行:

Integer.parseInt(a);

什么都不做-你马上把结果扔掉。它不会在适当的地方修改字符串或类似的东西(好吧,我想如果他们输入的不是整数,它会抛出一个异常,但这似乎不是你想用这行来做的。
至少,您应该将方法的返回类型更改为 int 把这行改成 return Integer.parseInt(a); .
(你也不应该每次都这样创建一个新的扫描仪-你应该重复使用同一个)。

相关问题