开发者

How to convert two strings to integers so math is correct?

I want the result no:5 but I get no:23

public class Assignment3
{
  public static voi开发者_开发知识库d main(String args[])
  {
    String str1 = "2";
    String str2 = "3";

  System.out.println("Result:" + (str1+str2) );
  }
}


If you want arithmetic to be done on integers, you need to tell your code to parse the values. Currently it's just using the string concatenation operator, because both of the operands (str1 and str2) are string expressions.

Try this:

public class Assignment3
{
  public static void main(String args[])
  {
    String str1 = "2";
    String str2 = "3";

    int num1 = Integer.parseInt(str1);
    int num2 = Integer.parseInt(str2);

    System.out.println("Result:" + (num1 + num2) );
  }
}

Note that when you're using "real" data (instead of hard-coded values which will definitely be valid here), Integer.parseInt will throw a NumberFormatException if you give it something like "x" instead of a number.


str1 and str2 are String objects. The + operation is defined for String objects and works like a concatenation of those Strings:

"one" + "two" -> "onetwo"
"1" + "2" -> "12"

If you need an arithmetic + operation, then you need numeric types (int, float, ...). In you're case, you'll have to parse the Strings to numeric values, like:

String str1 = "2";
int int1 = Integer.parseInt(str1);  // int1 is now 2

public class Assignment3
{
  public static void main(String args[])
  {
    String str1 = "2";
    String str2 = "3";

    // `+` operation on Strings
    System.out.println("Concatenation:" + (str1+str2) );

    // `+` operation on integers
    System.out.println("Addition:" + (Integer.parseInt(str1)+Integer.parseInt(str2)) );
  }
}


Integer.parseInt(String string);


You need to use parseInt(). The "+" operator is used in Java to concatenate two strings as well as to add two numbers. So you have to convert the strings to an integer to be able to add them with the "+" operator.

EDIT:

There is also parseFloat() and parseDouble() if you are working with decimal numbers


How about this?

class Assignment3 
{ 
  public static void main(String args[]) 
  { 
    String str1 = "2"; 
    String str2 = "3"; 

    System.out.println("Result:" + (Integer.parseInt(str1)+Integer.parseInt(str2)) ); 
  } 
}


You are treating numerical strings as textual strings, but actually you need to parse the strings to Integer.

public class Assignment3
{
  public static void main(String args[])
  {
    String str1 = "2";
    String str2 = "3";

  System.out.println("Result:" + (Integer.parseInt(str1)+Integer.parseInt(str2)) );
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜