简体   繁体   中英

error converting different data types (int and strings)

I'm trying to create a temperature converter where the user enters a temperature in Fahrenheit and it returns it in Celsius. Here's the code:

import javax.swing.*;

public class tempconv {

    public static void main (String[]args) {
        int fahr, cel;
        String fahrstring;

        fahrstring = JOptionPane.showInputDialog(valueof("Enter your temperature in F:"));
        fahr = new int[fahrstring];
        cel = (fahr - 32) * 5/9;

        JOptionPane.showMessageDialog(null, "The temperature in c is " + cel);
    }

}

I'm trying to convert the input dialog given into a int but the compiler stops me saying:

error: cannot find symbol
 fahrstring = JOptionPane.showInputDialog(>valueof("Enter your temperature in F:"));

so it must be a syntax error. According to the compiler I also got another error saying

tempconv.java:10: error: incompatible types: int[] cannot be converted to int
                  fahr = >new int[fahrstring];

how would the correct code be written and what exactly am I doing wrong?

use double rather than int as temperature may be 29.5 sometimes

double fahr = Double.parseDouble(fahrstring);
double c = ((fahr - 32) * (5/9));

Hope your problem is solved . keep coding good luck.

Another way to convert fahrstring to an int is by using the function:

Integer.parseInt(fahrstring)

(Here is a tutorial which demonstrates parseInt) http://www.tutorialspoint.com/java/lang/integer_parseint.htm

About the incompatible types error:

int fahr is an integer and new int [fahrString] will create an array object. fahr=new int [fahrstring] means you are trying to assign an array object to an int variable. This is obviously not going to work.

What can you do about it?

  • Change int fahr to int fahr[] and the compatibility error wouldn't show up again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM