I am making a calculator in java . After entering the string, for calculation, I try to convert it into numbers. In the C language it would be easy, there char
is easy to convert to int, but here the string turns into String
, and it is not clear how to process it into int
. String
doesn’t look like an array. If you try to display as: String [1], String [2], String [3] ...
– an error. Is it possible, somehow, to split String
into characters and convert into a table of corresponding values of type int
? (output characters to numbers)
Answer 1, authority 100%
is very simple:
int num = Integer.parseInt ("12345");
Answer 2, authority 88%
String (String
) in Java is an OOP wrapper over an array of character primitives (char
).
Thus, you can decompose String
into a char
array using the String # toCharArray ()
method:
String string = "A string is an array of letters";
char [] charArray = string.toCharArray ();
System.out.println (charArray [0]); // prints "C"
There is also a static method parseInt
in the Integer
class, which takes a string and outputs a number.
String string = "42";
int awesomeParsedInteger = Integer.parseInt (string);
System.out.println (awesomeParsedInteger); // prints "42"