如何在java中拆分整数?

如何在java中拆分整数?,java,Java,我试着把整数变成一个字符串,然后像那样把它拆分,但是我得到了一个错误,因为我必须把这个数字乘以一个字符串,但显然我不能。这是我的密码 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); Scan

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

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);
 }
}

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

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

然后,您可以通过正确的等式变换
英尺
英寸
,以获得公制高度

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;
您的身高(以英尺为单位)现在在
标记[0]
中,因此我假设您正在寻找类似的东西:

heightInches = (Integer.parseInt(token[0]) * 12) + Integer.parseInt(token[1]);
该方法可用于读取
英尺
重量
的值。即使同时输入值,该方法也将使用空格作为分隔符:

int feet = bmi1.nextInt();
int height = bmi1.nextInt();

除了前面的两个答案,你已经声明了
heightFtInches
int
,但我认为它应该是
字符串
,这样你就可以使用
split()
方法了。

你还没有告诉我们你想要实现什么,这让你很难得到帮助。他几乎做到了,但如果没有一个简单的例子,这是令人困惑的。我们不需要查看任何BMI内容。向我们显示您拥有的内容和您想要的内容。对于当前项目,您只需要并且应该有一个扫描仪对象。有时您需要多个输入,但它们不会扫描相同的输入(这里是System.in)。去除体重指数2和体重指数3。还要学习和使用Java命名约定,这样您就不会在代码中混淆我们。变量名称(例如扫描器变量)以及方法名称应以小写字母开头,而类名应以大写字母开头。我会将我的Scanner变量命名为Scanner。它很清楚,切中要害,并且描述了它是什么。那么您完全依赖于您的用户使用正确的格式输入数据?我认为这不会有好的结果,当然也不会没有一些错误处理。OP已经在对int weightPounds使用nextInt()。没有理由它们不能再次用于读取
英尺
&
高度
-更新我知道,我刚刚澄清了这个方法的存在。我必须乘以这个整数,所以我不能把它变成字符串。是的,但是你可以使用
integer.parseInt(标记[0])
先转换一个值,然后再转换另一个值(使用
Integer.parseInt(标记[1]);
),您将能够对得到的
int
s进行算术运算。。
heightInches = (Integer.parseInt(token[0]) * 12) + Integer.parseInt(token[1]);
int feet = bmi1.nextInt();
int height = bmi1.nextInt();