【问题标题】:How do I separate a float number that was input with string?如何分隔用字符串输入的浮点数?
【发布时间】:2016-01-03 15:02:13
【问题描述】:

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

    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.");

           }
        }

    }

程序显示此错误:

【问题讨论】:

  • “只取浮动部分”是什么意思?你的意思是“TEMP”之后的所有内容吗?如果是这样,substring 可能是你的朋友......
  • 它是一个字符串。找出数字从哪里开始,提取字符串的那部分,然后stackoverflow.com/questions/7552660/…
  • 作为建议,您要为此使用Scanner#nextLine 而不是Scanner#next,因为后者只会读取"TEMP" 而不是浮动部分。
  • Jon Skeet,是的,TEMP 之后的所有内容。这意味着它应该忽略 TEMP 并且只取数字。

标签: java string char java.util.scanner user-input


【解决方案1】:

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

例子:

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

【讨论】:

  • 行不通,因为字符串x= TEMP 10.5,那么它如何忽略TEMP而只考虑10.5?
  • @Esha 再次检查答案。
【解决方案2】:

您可以使用以下方法:

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

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

【讨论】:

    【解决方案3】:

    你的代码的问题在于你使用了

    String input = s.next();
    

    这只返回TEMP。你需要使用

    String input = s.nextLine();
    

    这应该返回完整的字符串。

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

    float tempFaren = celcius*1.8f + 32.0f;
    

    【讨论】:

      【解决方案4】:

      试试这样的

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

      【讨论】:

        【解决方案5】:

        可以使用indexOf查找第一个空格,substring获取空格位置后字符串的test,parseFloat将字符串中的数字解析为float:

        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+", ""));
        

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

        【讨论】:

        • janos,谢谢你的好回答。但这无济于事。请看我已经更新了我的帖子。我在那里发布了我的错误。
        • janos,我的朋友不要生气。当然你的回答有帮助。没有它我做不到。然而,非常感谢 gre_gor,因为他指出了重要的事情。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 2012-02-01
        • 2019-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多