2013-08-27 3 views
3

Я новичок в Java и все еще пытаюсь изучить свой путь. Сегодня мой учитель дал задание, где мы делаем калькулятор BMI на Java. Один из шагов состоит в том, чтобы показать категории BMI. Таким образом, пользователь сможет посмотреть на него и посмотреть, где они находятся. Я сделал все остальное, но я столкнулся с проблемой.Калькулятор BMI в Java

Вот сценарий:

import java.util.Scanner; 

public class BMI { 
    public static void main(String[] args){ 

     Scanner input = new Scanner(System.in); 

     double weight = 0.0; 
     double height = 0.0; 
     double bmi = 0.0; 

     System.out.print("Enter your weight in pounds: "); 
     weight = input.nextInt(); 

     System.out.print("Enter your height: "); 
     height = input.nextInt(); 

     bmi = ((weight * 703)/(height * height)); 

     System.out.printf("Your BMI is", bmi); 

     System.out.println("BMI VALUES"); 
     System.out.println("Underweight: Under 18.5"); 
     System.out.println("Normal: 18.5-24.9 "); 
     System.out.println("Overweight: 25-29.9"); 
     System.out.println("Obese: 30 or over"); 
    } 
    } 

Вот результат:

Your BMI isBMI VALUES 
Underweight: Under 18.5 
Normal: 18.5-24.9 
Overweight: 25-29.9 
Obese: 30 or over 

Что я делаю не так и как это исправить?

ответ

8

Попробуйте это:

System.out.printf("Your BMI is %f\n", bmi); 

Вы также можете печатать так:

System.out.println("Your BMI is " + bmi); 
+0

Спасибо за помощь, которая работала :) – ChrisD93

+0

Добро пожаловать :) –

+0

@ThatOneDude - если это решить вашу проблему, вы для ответа необходимо нажать на флажок. – JoshDM

13

Вы забыли заполнитель для bmi (и терминатор линии):

System.out.printf("Your BMI is %f\n", bmi); 

Вот formatting syntax guide для справки.

+1

(btw, 'bmi' выглядит как' double', а не 'int'.) –

+0

@DennisMeng Вы правы, изменились на '% f'. – rgettman

5

В то время как вы используете printf, следующее работает:

System.out.println("Your BMI is " + bmi); 
1

В идеале вы должны напечатать поплавки/удваивается в читаемом формате значение Обычно ИМТ измеряется до 2 знака после запятой

System.out.format("Your BMI is %.2f%n",bmi); 
0

Вероятно, это больше кода, но вы можете использовать JOptionPane

input = JOptionPane.showInputDialog("What is you weight in pounds?"); 
     weight = Double.parseDouble(input); 

     input = JOptionPane.showInputDialog("What is your hight is inches?"); 
     height = Double.parseDouble(input); 
0

m ismatch между объявлением типа переменной (double) и объявлением типа ввода пользователя (nextInt) Я бы использовал nextDouble в качестве типа ввода, если вы хотите сохранить тип переменной как двойной.

-2

A: Я не уверен, что bmi = ((weight * 703)/(height * height)); является правильным.

я наткнулся на формулу, которая может работать для вас BMI = ((weight/(height * height))* 10000;

B: System.out.printf(“Your BMI is”, bmi); не требуется System.out.prinln(“ Your BMI is “ + BMI);

Я надеюсь, что это работает для вас удачи держать

0

Вы могут использовать такие массивы:

public static void main(String[] args) { 
    double[] ht = new double[5]; 
    double[] wt = new double[5]; 
    double[] bmi = new double[5]; 
    String[] sht = new String[5]; 
    String[] swt = new String[5]; 

    for (int i = 0; i < ht.length; i++) { 
     sht[i] = JOptionPane.showInputDialog("Enter Hight"); 
     swt[i] = JOptionPane.showInputDialog("Enter Weight"); 
     ht[i]=Double.parseDouble(sht[i]); 
     wt[i]=Double.parseDouble(swt[i]); 
     bmi[i]=wt[i]/(ht[i]*ht[i]); 
     System.out.println("BMI IS "+bmi[i]+"Kg/m2"); 
     JOptionPane.showMessageDialog(null,"BMI IS "+bmi[i] +"Kg/m2"); 
     if(bmi[i]>25){ 
      JOptionPane.showMessageDialog(null,"YOU ARE AT RISK"); 
      System.out.println("YOU ARE AT RISK"); 
     }else { 
      JOptionPane.showMessageDialog(null,"YOU ARE Healthy"); 
      System.out.println("YOU ARE Healthy "); 
    } 

    } 
} 
0

https://github.com/arghadasofficial/BMI/blob/master/src/argha/bmi/Bmi.java

public class Bmi { 

    //Variables 
    private double result; //Stores the result 
    private String bmi; //Stores the Bmi result in String 
    private String status; //Stores the status (Normal......) 
    private static DecimalFormat decimalFormat = new DecimalFormat(".#"); //Formating the result 

    /** 
    * Get the BMI from calculation and returns the result in String format 
    * 
    * @return BMI 
    */ 
    public String getBmi() { 
     /** 
     * Following code example : bmi = decimalFormat.format(result); 
     * 
     * if bmi is 23.12345 then remove 2345 and return 23.1 using DecimalFormat class provided by Java 
     * 
     */ 
     bmi = decimalFormat.format(result); 
     return bmi; 
    } 

    /** 
    * Get the status according to the BMI result and returns the Status in 
    * String format 
    * 
    * @return Status 
    */ 
    public String getStatus() { 
     return status; 
    } 

    /** 
    * Get weight and height in double format and do the calculation for you 
    * 
    * @param weight - accepts weight in kilograms 
    * @param height - accept height in centimeters 
    */ 
    public void calculateBmi(double weight, double height) { 
     /** 
     * First get weight and height then convert height to meters then 
     * multiply the height itself to height and then divide the height with 
     * weight then set the actual value to result variable 
     */ 

     //Convert the height from cm to m 
     double meters = height/100; 

     //Multiply height by height 
     double multiply = meters * meters; 

     //divide the height with weight in kg 
     double division = weight/multiply; 

     //set the value to result variable 
     result = division; 

     //call checkStatus method for checking Status 
     checkStatus(); 
    } 

    /** 
    * Private method for checking bmi and returns the status It remains private 
    * because we don't need to access this from somewhere else. 
    */ 
    private void checkStatus() { 
     /** 
     * Check : 
     * 
     * if BMI is less than 18.5 then set status to Underweight if BMI is 
     * greater than 18.5 and less than 25 then set status to Normal if BMI 
     * is greater than 25 and less than 30 then set status to Overweight if 
     * BMI equals to 30 or greater than 30 then set status to Obese 
     */ 
     if (result < 18.5) { 
      status = "Underweight"; 
     } else if (result > 18.5 && result < 25) { 
      status = "Normal"; 
     } else if (result > 25 && result < 30) { 
      status = "Overweight"; 
     } else if (result == 30 || result > 30) { 
      status = "Obese"; 
     } 
    } 
} 
+0

Спасибо за ваш ответ. Подумайте о расширении своего ответа, объяснив, как этот код решает проблему. –

+0

Bmi bmi = новый Bmi(); \t bmi.calculateBmi (65, 162); \t System.out.println (bmi.getBmi()); \t System.out.println (bmi.getStatus()); –

+0

Отлично, рассмотрите возможность редактировать свой пост и добавить это объяснение. –