如何分隔用字符串输入的浮点数?

How do I separate a float number that was input with string?

在我的程序中,用户用 TEMP 输入一个 float 数字(例如 TEMP 10.05)。 该程序应仅采用 float 部分并将其转换为票价。最后打印出浮点数的结果。 我该怎么做?

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("The following program takes a float value with the word 'TEMP'in celcius, and converts into farenheit");
        System.out.println("Enter the temperature with TEMP: ");

        while (true) {
            String input = s.next();
            //converting into farenheit
           if (input != null && input.startsWith("TEMP")) {
                float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
float tempFaren=celcius+32.8;
               // float=result
                System.out.println("Temperature in farehheit is : "+tempFaren+ " F.");

           }
        }

    }

程序显示此错误:

您可以使用 Float.parseFloat(yourString);

示例:

    String x = "TEMP 10.5";
    float y = Float.parseFloat(x.substring(5,x.length()));
    System.out.println(y);

您可以使用 indexOf 查找第一个 space,使用 substring 获取 space 位置之后的字符串的测试,并使用 parseFloat 将字符串中的数字解析为浮点数:

float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));

同样的事情分解为步骤:

int spacePos = input.indexOf(' ');
String celsiusStr = input.substring(spacePos + 1);
float celsius = Float.parseFloat(celsiusStr);

更新

您修改后的代码也无法编译(您在 "celcius" 中存在输入错误以及其他问题)。

编译并正确解析浮点部分:

String input = "TEMP 10.5";
float celsius = Float.parseFloat(input.substring(input.indexOf(' ') + 1));
float tempFaren = celsius + 32.8f;
System.out.println("Temperature in farehheit is : " + tempFaren + " F.");

最后, 在字符串末尾提取浮点值的另一种方法是从开头去除非数字值,例如:

float celsius = Float.parseFloat(input.replaceAll("^\D+", ""));

免责声明: none 我上面给出的示例将适用于所有可能的输入,它们是根据您提供的示例输入量身定制的。如有必要,它们可以变得更坚固。

尝试这样的事情

    while (true) {
          String input = s.nextLine();
           //converting into farenheit

        if (input != null && input.startsWith("TEMP")) {
            try{
                double faren=Double.parseDouble(input.substring(input.lastIndexOf(' ')+1))+32.8;
                //float tempIntoFarenheit= input+32.8
                System.out.println("Temperature in farenheit: "+faren);

            }catch(Exception e){
                System.out.println("Something was wrong with the temperature, make sure the input has something like 'TEMP 50.0' ");
                System.out.println(e.toString());
            }


        } else {
            System.out.println("Wrong input. Try again: ");
        }
    }

你的代码有问题是你使用了

String input = s.next();

仅此 return 秒 TEMP。你需要使用

String input = s.nextLine();

这应该是 return 完整的字符串。

与你的问题无关,你也converting the temperatures错了。应该是

float tempFaren = celcius*1.8f + 32.0f;

您可以使用以下方法:

static float extractFloatWithDefault(String s, float def) {
  Pattern p = Pattern.compile("\d+(\.\d+)?");
  Matcher m = p.matcher(s);
  if ( !m.find() ) return def;
  return Float.parseFloat(m.group());
}

像这样:

     while (true) {
        String input = s.next();
        //converting into farenheit
       if (input != null && input.startsWith("TEMP")) {
            float celsius = extractFloatWithDefault(input, -999);
            if ( celsius > -999 ) {
              float tempFaren=celcius+32.8;
              System.out.println("Temperature in farehheit is : "+tempFaren+ " F.");
            }
            else System.out.println("Please include a number");
       }
    }

此方法将提取它在字符串中找到的第一个数字并使用它,或者 return 如果没有有效的浮点数或整数,则使用默认值。