将英尺和英寸换算为英寸(多个输入变为一个输入)

时间:2019-12-03 18:58:17

标签: java bluej

这个程序让我很困惑。我正在尝试找出一种从此转换输入的方法:

    System.out.print("Enter your height in inches (e.g. 57): ");
    String height = in.nextLine();
    height += in.nextLine();
    System.out.println();

并将其变成英寸。如何将英尺与英寸分开,将所说的英尺改为英寸,然后再次将它们合并为英寸?

3 个答案:

答案 0 :(得分:1)

System.out.print("Enter your height in inches (e.g. 57): ");
int heightInInches = in.nextInt();
int heightInFeet = heightInInches / 12;
int heightInchesRemaining = heightInInches % 12;
System.out.println(heightInFeet + "\' " + heightInchesRemaining + "\""); 

您可以这样做将其转换为英尺和英寸格式。然后,对您描述的其余操作进行所需的操作。

答案 1 :(得分:0)

首先,您的问题和示例代码令人困惑,因此我将以您的最后声明为基础。据我了解,您要求用户先输入以英尺为单位的身高,然后输入剩余的英寸数,然后将此信息仅转换为英寸数(例如5'7到67英寸)

System.out.print("Enter your height in feet. (e.g, 5 if your height is 5'7) : ");
int height = in.nextInt() * 12;
System.out.print("Enter your height in inches (e.g, 7 if your height is 5'7) : ");
height += in.nextInt();
System.out.println(height);

答案 2 :(得分:0)

您可以执行以下操作:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.print("Enter your height in inches (e.g. 57): ");
        String height = in.nextLine();
        int length=Integer.parseInt(height);
        int feet=length/12;
        int inches=length%12;
        System.out.println(feet+"'"+inches+"\"");

        int combined=feet*12+inches;
        System.out.println("Height after combining feet and inches again: "+combined);
    }
}

示例运行:

Enter your height in inches (e.g. 57): 57
4'9"
Height after combining feet and inches again: 57