用Java转换测量值

时间:2016-02-09 22:30:32

标签: java

因此,在我的作业中,我需要编写一个程序,询问用户的身高和体重,并将其从英尺,英寸转换为米,厘米。以及将重量从磅转换为千克。我所获得的程序无法进行5 7之类的测量并进行转换。 这是一个实际的家庭作业问题:

  1. 程序会询问用户的姓名。该程序将提示"您的名字是什么?"用户输入他/她的名字。

    1. 然后程序应询问用户的身高和体重。

    2. 然后应该在单独的行上打印,"用户的姓名"您在公制系统中的高度是(打印出以米和厘米为单位的高度。例如,您在公制系统中的高度为1米45厘米。

    3. 然后应以KG和克打印重量(与公制中的重量相同----)

  2. 这是我到目前为止所提出的:

    package extracredit;
    
    /**
     *
     * @author Kent
     */
    import java.util.Scanner;
    
    public class Extracredit {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.println("What is your name? ");
            String name = in.next();
            System.out.println("What is your height? ");
            Double Height = in.nextDouble();
            System.out.println("What is your weight? ");
            Double Weight = in.nextDouble();
            System.out.println(name);
            System.out.print("Your height in metric system: ");
            System.out.println(Height * .3048);
            System.out.println("Your weight in kg: ");
            System.out.println(Weight*0.453592);
        }
    
    }
    

4 个答案:

答案 0 :(得分:1)

简单的解决方案就是这样。

您问"what is your height in feet",让它为int feet

然后"and how many inches",让它为int inches

然后分配int totalInches = 12*feet + inches

其他解决方案包括在'字符上拆分字符串并解析int值。

或使用正则表达式,但我猜这将是一个比你目前所追求的更高级的主题。

答案 1 :(得分:0)

你可以尝试这种方法,它会要求脚的“高度”格式,然后将其转换为英寸/厘米。

    Scanner in = new Scanner(System.in);
    System.out.println("Please enter your height (feet'inches\")");
    String heightInput=in.next();
    int heightInInches;
    heightInInches=Integer.parseInt(heightInput.split("'")[0])*12;
    //Calculate feet
    heightInInches+=Integer.parseInt(heightInput.split("'")[1].replaceAll("[^\\d.]",""));
    //Celculate remaining inches, regex is used to remove the "

    System.out.println("Height in inches: "+heightInInches);
    System.out.println("Height in centimetres: "+heightInInches*2.54);
    //Multiply by 2.54 to convert to centimetres

答案 2 :(得分:0)

如果您接受格式化输入,那么您应该使用带有组的显式正则表达式来表示值。这样,您就可以免费获得所有错误检查作为解析的一部分。

例如:

Pattern heightPattern = Pattern.compile("(\\d+)'(\\d+)\"");
Matcher heightMatcher = heightPattern.match(in.next());
while (!heightMatcher.matches()) {
    System.out.println("Please re-enter your height in the format n'n\"");
    heightMatcher = heightPattern.match(in.next());
}
int feet = Integer.valueOf(heightMatcher.group(1));
int inches = Integer.valueOf(heightMatcher.group(2));

答案 3 :(得分:-2)

您可以将输入作为字符串获取并将其拆分为

String height = in.next();
String[] splitHeight = height.split("'");
int feet = Integer.valueOf(splitHeight[0]);
int inches = Integer.valueOf(splitHeight[1]);

在这里,您必须考虑splitHeight[1]可能为null(如果输入字符串不包含')。 之后,您可以使用feet * 12 + inches以英寸为单位进行计算。