你如何在java中拆分整数?

时间:2013-10-16 21:16:15

标签: 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);
    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 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

在这里拆分字符串并且不要使用它(在将heightFtInches更改为字符串后很好)

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

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

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

然后,您可以通过正确的equatiob多次feetinches来获取公制高度

答案 2 :(得分: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]);

答案 3 :(得分:0)

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