2015-04-26 3 views
-2

Эта программа компилируется и запускается, но не вычисляет страховую премию. Я работаю над этим несколько дней и не могу понять. Раньше он запускался в другой версии, но мы должны иметь 2 класса сейчас, и теперь он не вычисляет страховку, или он отображается как ноль в каждом ответе. Мы также должны использовать панели для ввода.Нужна помощь в поиске ошибки в этой программе, компилируется, но не нужна компьютерная цифра

// The Premium class represents an insurance premium cost for an individual policy. 


public class Premium 
{ 
    private int a; // to hold customer age 
    private int h; // to hold customer height 
    private int w; // to hold customer weight 
    private String s; // to hold smoking status 

    int i; // to hold insurance price 

    //setAge set's customer's height 
    public void setAge(int age) 
    { 
     a = age; 
    } 

    //setHeight set's customer's height 
    public void setHeight(int height) 
    { 
     h = height; 
    } 

    //setWeight set's customer's weight 
    public void setWeight(int weight) 
    { 
     w= weight; 
    } 

    //setSmoke set's customer's smoking status 
    public void setSmoke(String smoker) 
    { 
     s = smoker; 
    } 


    //getHeight method returns customer's height 
    public int getHeight() 
    { 
     return h; 
    } 

    //getWeight method returns customer's weight 
    public int getWeight() 
    { 
     return w; 
    } 

    //getAge method returns customer's age 
    public int getAge() 
    { 
     return a; 
    } 

    //getSmoke returns customer's smoking status 
    public String getSmoke() 
    { 
     return s; 
    } 


    //constructor 
    public Premium(int age, int height, int weight, String smoker) 
    { 
    age = a; 
    height = h; 
    weight = w; 
    smoker = s; 
    } 


    //calculate individual insurance price method 
     public static int calculateInsurance(int age, String smoker) 
     { 
     //variables 
     String smoking = "smoker"; 
     int insurance; 
     final int insuranceBase = 400; 

     //create new instance of BMI class 
      BMI custBMI = new BMI(); 

      double bmi= custBMI.calculateBMI(); 


     //calculate insurance 
     if (age > 50){ 
      insurance = insuranceBase + 100; 
      } 
      else{ 
      insurance = insuranceBase; 
      } 

      if (smoker.equals('Y')){ 
      insurance += 150; 
      }else { 
      insurance +=0; 
      } 

      if (bmi > 40){ 
      insurance += 100; 
      } else { 
      insurance +=0; 
      } 

     return insurance; 

     } 

    //setInsurance method sets insurance price 
    public void setInsurance(int insurance) 
    { 
     i = insurance; 
    } 

    //getInsurance method returns insurance price 
    public int getInsurance() 
    { 
     return i; 
    } 



    public void displayPrice() 
    { 
    System.out.println("Insurance Premium Cost: " + getInsurance()); 
    } 
} 

************************************* 
/** BMI class calculates customer's BMI 
*/ 

public class BMI 
{ 
    private int h; //to hold customer's height 
    private int w; //to hold customer's weight 

    //setWeight set's customer's weight 
    public void setWeight(int weight) 
    { 
     w= weight; 
    } 
    //set height set's customer's height 
    public void setHeight(int height) 
    { 
     h = height; 
    } 

    //getWeight method returns customer's weight 
    public int getWeight() 
    { 
     return w; 
    } 

    //getHeight method returns customer's height 
    public int getHeight() 
    { 
     return h; 
    } 

    // calculate customer's BMI 
    public double calculateBMI() 
     { 
     double bmi; 
     //calculate BMI 
     bmi = (getWeight() * 703)/(getHeight() * getHeight()); 

     return bmi; 
     } 


} 
******************************************* 

    This program will demonstrate the Premium and BMI classes. This program will prompt users for input, 
    use that input to calculate BMI and their insurance rate. 
    Output will be the customer profile: name, age, smoker status, height, weight and insurance premium cost. 
    Program will then ask user if they want to create another profile. 
*/ 

import javax.swing.JOptionPane; //required for dialog boxes 

public class Project2_1 
{ 
    public static void main(String[] args) 
    { 
     String submit; 

     System.out.println("Welcome! Please fill out the following information to get an insurance premium quote."); 
     System.out.println(); 


    do{ 
    //get customerInfo method promts user for their information 
     String input; // to hold user input 
     String fname; 
     String lname; 
     int age; 
     String smoker; 
     int height; 
     int weight; 


     //get customer input 
     fname =JOptionPane.showInputDialog("Please enter your first name: "); 
     lname =JOptionPane.showInputDialog("Please enter your last name: "); 
     input = JOptionPane.showInputDialog("Please enter your age: "); 
     age = Integer.parseInt(input); 
     //validate input 
     while (age < 0 || age > 141) 
     { 
     input = JOptionPane.showInputDialog("Invalid input! Age must be 1 through 140. Please enter your age: "); 
     age = Integer.parseInt(input); 
     } 

     smoker = JOptionPane.showInputDialog("Are you a smoker? Please enter Y or N: "); 
     //validate input 
     if (!smoker.equalsIgnoreCase("Y")) 
     { 
     System.out.println(""); 
     }else if (!smoker.equalsIgnoreCase("N")) 
     { 
     smoker = JOptionPane.showInputDialog("Invalid input! Are you a smoker? Answer must be Y or N: "); 
     } else 
      { 
       System.out.println(""); 
       } 
     input = JOptionPane.showInputDialog("Please enter your height in inches: "); 
     height = Integer.parseInt(input); 
     //validate input 
     while (height < 0 || height > 108) 
     { 
     input = JOptionPane.showInputDialog("Invalid input! Height must be between 1 and 108 inches. Please enter your height in inches: "); 
     height = Integer.parseInt(input); 
     } 
     input = JOptionPane.showInputDialog("Please enter your weight in pounds: "); 
     weight= Integer.parseInt(input); 
     //validate input 
     while (weight < 0 || weight > 800) 
     { 
     input = JOptionPane.showInputDialog("Invalid input! Weight must be between 1 and 800 pounds. Please enter your weight in pounds: "); 
     weight = Integer.parseInt(input); 
     } 

    //create instance of the Premium class 

    Premium customer = new Premium(age, height, weight, smoker); 


    //call method to display individual results     
    displayResults(fname, lname, age, smoker, height, weight);  

    //get data from customer and displays calculated results 
     customer.displayPrice(); 

    submit =JOptionPane.showInputDialog("Would you like to submit another profile? Enter Y or N: "); 
    //validate input 
     if (!submit.equalsIgnoreCase("Y")) 
     { 
     System.out.println(""); 

     } else if (!smoker.equalsIgnoreCase("N")) 

      { submit = JOptionPane.showInputDialog("Invalid input!Another profile? Answer must be Y or N: "); 

      } else { 
       System.out.println(""); 
      } 
     } while (submit.equalsIgnoreCase("Y")); 

    } 

     //method to display customer profile information 
    public static void displayResults(String fname, String lname, int age, String smoker, int height, int weight) 
     { 

      //Output 
      System.out.println(" "); 
      System.out.println("First Name:    " + fname); 
      System.out.println("Last Name:    " + lname); 
      System.out.println("Age:     " + age); 
      System.out.println("Smoking Status:   " + smoker); 
      System.out.println("Height(in.):   " + height); 
      System.out.println("Weight(lbs):   " + weight); 
      System.out.println(" "); 
    } 

} 
+1

На это лучше всего ответить, используя отладчик, чтобы протестировать вашу программу при ее запуске. –

+1

Чтобы начать, посмотрите на свой конструктор Premium. Вы проходите с течением времени, но в теле конструктора вы пишете age = a, когда похоже, что это должен быть возраст. Повторите свой код, внимательно, ищите эти семантические ошибки. – MarsAtomic

ответ

0

Если вы не получаете ошибок компилятора, это логическая ошибка в вашем коде.

Выглядит как метод calculateInsurance никогда не называется.

+0

Спасибо, я исправил их сейчас, я думаю, то же самое, работает, компилируется, но нет страховой цены. – PDL

+0

// setInsurance метод устанавливает страховую цену public void setInsurance (int insurance) { calculateInsurance (a, s); i = страхование; } // getInsurance метод возвращает страховую цену public int getInsurance() { return i; } общественного недействительными displayPrice() { System.out.println ("Страховая премия Стоимость:" + getInsurance()); } } – PDL

+0

Ну, тогда у вас все еще есть логическая ошибка, связанная с объектом вашего клиента. Вы использовали как client.calculateInsurance(), так и customer.displayPrice()? – Kyle556

Смежные вопросы