【问题标题】:I need help fixing my code, I'm unsure of how to make it give me a total in the very end我需要帮助修复我的代码,我不确定如何让它最终给我一个总数
【发布时间】:2020-10-06 11:44:57
【问题描述】:

下面是我正在处理的代码,我将显示输入和我收到的输出与我想要的输出。我正在尝试获取代码以在最后为我提供现场与非现场工作人员的总数。

string name, DOB, status;
int hours;
System.out.print("how many worker: ");
       int number = sr.nextInt();

       int countworker = 0;
       for (int l = 0; l < number; l++) {
     System.out.print("What is ther name ");
           name = sr.next();

           System.out.print("What is their DOB ");
           DOB = sr.next();

           System.out.print("How many hours is he/she working ");
           hour = sr.nextInt();

           System.out.println("What is their Status: fulltime_onsite, parttime_onsite, offsite  ");
           status = sr.next();
int countoffsite = 0, countonsite = 0;

          switch (status) {
case "fulltime_onsite":
    System.out.println("pa " + 3465 ) ; 
    countonsite++;
    break;
case "parttime_onsite":
    System.out.println("pay" + 1305) ) ; 
    countonsitee++;
    break;
case "offsite ":
    System.out.println("pay" + 1620) ) ; 
    countoffsite++;
  break;
}

这是我的输出,我需要帮助让程序告诉我 3 名学生中有多少学生不在现场,有多少学生在现场。

name: tom
DOB: 12/3/98
hour: 45
status: fulltime_onsite
pay: 3465
name: jerry 
DOB: 3/6/90
hour: 45
status: parttime_onsite
pay: 1305
name: harry
DOB: 6/7/89
hour: 15
status: offsite
pay: 1620

我希望代码以

结尾
Off Site: 1
 On site: 2

【问题讨论】:

    标签: java loops math count switch-statement


    【解决方案1】:

    如果显示 System.out.println() 在 for 循环之外,只需将 countonsite、countoffside 变量放在 for 循环之外。

    这些变量的作用域是 for 循环的局部变量。这意味着它们在 for 循环之后不存在。通过将它们放在 for 循环之外,您可以访问这些变量在循环之外保存的值。因此,您可以使用它们来显示。

    【讨论】:

      【解决方案2】:

      假设您获得了问题中显示的输出。我相信如果您将两个变量都放在 for 循环之外应该可以解决问题。您可以稍后打印结果。

      int countoffsite = 0, countonsite = 0;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-06
        • 2021-01-27
        相关资源
        最近更新 更多