-2

我曾尝试将整数变成一个字符串,然后像那样拆分它,但后来我得到一个错误,因为我必须乘以那个字符串,但显然我不能。这是我的代码。

import java.util.Scanner;

public class BMI {
 public static void main(String[] args)  {
    Scanner BMI1 = new Scanner(System.in);
    Scanner BMI2 = new Scanner(System.in);
    Scanner BMI3 = new Scanner(System.in);
    String name;
    int weightPounds;
    int heightFtInches;
    int heightInches;
    double weightKg;
    double heightM;

    System.out.print("Please enter your name (e.g. First Last): ");
    name = BMI1.nextLine();

    System.out.print("Please enter your weight in pounds (e.g. 150): ");
    weightPounds = BMI2.nextInt();

    System.out.print("Please enter your height in feet and inches (e.g. 6, 8): ");
    heightFtInches = BMI3.nextLine();
    String[] token = heightFtInches.split(",");
    System.out.println();

    System.out.println("Body Mass Index Calculator");
    System.out.println("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#");
    System.out.println();

    weightKg = weightPounds / 2.2;
    heightInches = heightFtInches * 12;


    System.out.println("Name: " + name);
    System.out.println("Weight in Kg: " + weightKg);
    System.out.println("Height in meters: " + heightInches);
 }
}
4

4 回答 4

1

nextInt方法可用于读取 和 的feetweight。即使同时输入值,该方法也会使用空格作为分隔符:

int feet = bmi1.nextInt();
int height = bmi1.nextInt();
于 2013-10-16T21:24:11.930 回答
0

添加到前两个答案中,您已声明heightFtInches为 anint但我认为它应该是 a String,因此您可以split()在其上使用该方法。

于 2013-10-16T21:24:41.930 回答
0

在这里您拆分字符串并且不使用它(在您更改heightFtInches为字符串之后)

String[] token = heightFtInches.split(",");

您想要的是将每个转换为 int (注意这是假设有效输入)

int feet = Integer.parseInt(token[0]);
int inches = Integer.parseInt(token[1]);

feet然后你可以inches通过正确的等式来获得公制高度

于 2013-10-16T21:21:18.023 回答
0
String[] token = heightFtInches.split(",");
System.out.println();

System.out.println("Body Mass Index Calculator");
System.out.println("#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#");
System.out.println();

weightKg = weightPounds / 2.2;
heightInches = heightFtInches * 12;

你现在的身高是英尺,token[0]所以我假设你正在寻找这样的东西:

heightInches = (Integer.parseInt(token[0]) * 12) + Integer.parseInt(token[1]);
于 2013-10-16T21:22:05.843 回答