【问题标题】:How would I use a while loop to get multiple inputs?我将如何使用 while 循环来获取多个输入?
【发布时间】:2020-05-02 08:46:52
【问题描述】:

我想编写一个程序,要求用户输入订票的客户数量,读取输入的数字,执行循环询问每个客户的年龄,并确定每个客户的单价。 到目前为止,我的代码只有 if else 语句:

if (customerP <4){
    System.out.println("The unit Price of customer 1 is: 0");
}else {
    if(customerP <13) {
        System.out.println("The unit price of customer 1 is: 5");
    }else {
        if(customerP <19) {
            System.out.println("The unit price of customer 1 is: 8");
        }else {
            System.out.println("The unit price of customer 1 is: 10");
        }
    }    
}

如何添加一个 while 循环来询问每个客户的年龄?

【问题讨论】:

  • 在一个命令中查看else if,避免像这里一样重叠

标签: java while-loop do-while


【解决方案1】:

给你:

Scanner scanner = new Scanner(System.in);

System.out.println("Enter No of Customers: ");
int noCustomers = scanner.nextInt();

if (noCustomers < 1) {
     throw new IllegalArgumentException("No of Customers has to be 1 or greater");
}

int[] customerAges = new int[noCustomers];

for (int i = 0; i < noCustomers; i++) {
    System.out.println("Enter age for customer: " + i);
    customerAges[i] = scanner.nextInt();
}

System.out.println("Ages: " + Arrays.toString(customerAges));

【讨论】:

    【解决方案2】:

    下面提供了使用while循环的代码

    Scanner sc = new Scanner(System.in);
    
    int customerCount = sc.nextInt();
    
    int[] ageOfCustomers = new int[customerCount];
    int i=0;
    while(customerCount-- > 0) {
    
        ageOfCustomers[i++] = sc.nextInt();
    }
    
    System.out.println(Arrays.toString(ageOfCustomers));
    

    【讨论】:

      猜你喜欢
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 2016-12-16
      • 2016-12-23
      • 2021-12-02
      • 1970-01-01
      相关资源
      最近更新 更多