汇总不同计算的结果

时间:2017-09-21 21:50:32

标签: java

这是我在这里发表的第一篇文章,请原谅我有任何格式错误。

因此,您可以看到我的计划要求性别,事故数量和汽车年份显示虚构的保险报价。

根据所有这些信息,我需要将保险费用的小计添加到最后。

我的代码一直在运行,直到总费用评论(将其全部发布以供参考)。我被困在那里因为性别有不同的基数。我试图想办法只做一个if语句,如果它与用户输入的性别相匹配。

有什么想法吗?

import java.util.*;
public class Insurance {
  public static void main(String [] args) {
    Scanner scanner = new Scanner(System.in);

   int currentYear = 2017; //used for calculating the age of the users car
   int maleGender = 1000;
   int femaleGender = 500;

   //Letting user know they are inputting data for car insurance purposes
   System.out.println("Car insurance questionnaire. Please input correct information when prompted.");

   // gender information from user
   System.out.println("What is your gender? m/f");
   String gender = scanner.next();

   // accident quantity information from user
   System.out.println("How many accidents have you had?");
   int acc = scanner.nextInt();

   // car year information from user
   System.out.println("What year was your car manufactured?");
   int carAge = scanner.nextInt();

   //if statements which refer to the users data input
    if (gender.equals("m")) {
     System.out.println("You are a male.\nThe base cost is $1000."); 
     } else {
     System.out.println("You are a female.\nThe base cost is $500.");
     }


     if (acc == 0) {
     System.out.println("You have no accidents. Insurance increase is $0.");
     } else if (acc >= 1) {
     System.out.println("You have " + acc + " accidents. Insurance increase is $" + acc * 100 + ".");
     }


     if (carAge >= 2007) {
      System.out.println("Your car is " + (currentYear - carAge) + " years old.\nYour car is still in warranty, no savings added.");
      } else 
      System.out.println("Your car is out of warranty, final cost is halved.");

      //Total cost
     /*
      if (carAge <= 2007) {
      System.out.println("Your total price is $" + ((acc * 100 + femaleGender) / 2) + ".");
      } else 
      System.out.println("Your total price is $" + (acc * 100 + femaleGender) + ".");
        */


 }
}

2 个答案:

答案 0 :(得分:0)

我不完全确定你想要如何计算你的结果,但是如果不想一直使用femaleGender但是依赖于性别不同的值,那么这样的事情可能会有所帮助:

int baseAmount = gender.equals("m") ? maleGender : femaleGender;
if (carAge <= 2007) {
    System.out.println("Your total price is $" + ((acc * 100 + baseAmount ) / 2) + ".");
} else 
    System.out.println("Your total price is $" + (acc * 100 + baseAmount ) + ".");
}

答案 1 :(得分:0)

int genderCost;

...

if (gender.equals("m")) {
    System.out.println("You are a male.\nThe base cost is $1000.");
    genderCost = maleGender;
} else {
    System.out.println("You are a female.\nThe base cost is $500.");
    genderCost = femaleGender;
}

...

if (carAge <= 2007) {
    System.out.println("Your total price is $" + ((acc * 100 + genderCost) / 2) + ".");
} else 
    System.out.println("Your total price is $" + (acc * 100 + genderCost) + ".");
}

在评估性别输入变量时,将性别金额放入变量genderCost,并在计算总数时使用genderCost

相关问题