0

In my program, a user inputs a float number with TEMP (for example TEMP 10.05). The program should take only the float part and convert it into fareheit. And finally printing out the result in float. How could I do that?

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

           }
        }

    }

The program shows this error:

enter image description here

Esha
  • 435
  • 2
  • 5
  • 12
  • What do you mean by "take only the float part"? Do you mean "everything after "TEMP "? If so, substring is probably your friend... – Jon Skeet Oct 06 '15 at 15:52
  • it's a string. figure out where the number starts, extract that part of the string, then http://stackoverflow.com/questions/7552660/java-convert-float-to-string-and-string-to-float – Marc B Oct 06 '15 at 15:53
  • As a recommendation, you want to use `Scanner#nextLine` for this and not `Scanner#next` because the latter will read `"TEMP"` only and not the float part. – Luiggi Mendoza Oct 06 '15 at 15:56
  • Jon Skeet, yes, everything after TEMP. that means it should ignore the TEMP and take only the number. – Esha Oct 06 '15 at 16:00

5 Answers5

1

You could use Float.parseFloat(yourString);

Example:

    String x = "TEMP 10.5";
    float y = Float.parseFloat(x.substring(5,x.length()));
    System.out.println(y);
ninesalt
  • 4,054
  • 5
  • 35
  • 75
1

The problem with your code is that you use

String input = s.next();

this only returns TEMP. You need to use

String input = s.nextLine();

this should return the full string.

And unrelated to you question, you are also converting the temperatures wrong. It should be

float tempFaren = celcius*1.8f + 32.0f;
gre_gor
  • 6,669
  • 9
  • 47
  • 52
0

You can use indexOf to find the first space, substring to get the test of the string after the position of the space, and parseFloat to parse the number from string into a float:

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

The same thing broken down to steps:

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

UPDATE

Your modified code doesn't compile either (you have typing error in "celcius", and other problems).

This compiles, and correctly parses the floating point part:

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

Finally, another way to extract the float value at the end of the string is to strip non-numeric values from the beginning, for example:

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

Disclaimer: none of the examples I gave above will work for all possible inputs, they are tailored to the example inputs you gave. They can be made more robust if necessary.

janos
  • 120,954
  • 29
  • 226
  • 236
  • janos, thanks for you nice answer. but it doesn't help. Please see I have updated my post. There I have posted my error. – Esha Oct 06 '15 at 16:42
  • janos, my frined dont be angry. Of course ur answer help. without it i couldnt make it. However the big thanks goes to gre_gor, because he pointed out the important thing. – Esha Oct 06 '15 at 19:54
0

Try something like this

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

You can use the following method:

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

Like this:

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

This method would extract the first number it finds in the strings and uses it or return the default value if there is no valid floating number or integer.

Eliran
  • 134
  • 4