And what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers - assuming that the string only contains numbers, otherwise the result is undefined. If the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
Answer from Óscar López on Stack OverflowAnd what is wrong with this?
int i = Integer.parseInt(str);
EDIT :
If you really need to do the conversion by hand, try this:
public static int myStringToInteger(String str) {
int answer = 0, factor = 1;
for (int i = str.length()-1; i >= 0; i--) {
answer += (str.charAt(i) - '0') * factor;
factor *= 10;
}
return answer;
}
The above will work fine for positive integers - assuming that the string only contains numbers, otherwise the result is undefined. If the number is negative you'll have to do a little checking first, but I'll leave that as an exercise for the reader.
If the standard libraries are disallowed, there are many approaches to solving this problem. One way to think about this is as a recursive function:
- If n is less than 10, just convert it to the one-character string holding its digit. For example, 3 becomes "3".
- If n is greater than 10, then use division and modulus to get the last digit of n and the number formed by excluding the last digit. Recursively get a string for the first digits, then append the appropriate character for the last digit. For example, if n is 137, you'd recursively compute "13" and tack on "7" to get "137".
You will need logic to special-case 0 and negative numbers, but otherwise this can be done fairly simply.
Since I suspect that this may be homework (and know for a fact that at some schools it is), I'll leave the actual conversion as an exercise to the reader. :-)
Hope this helps!
To improve your intToString() method you should consider using a StringBuilder, and specifically the method StringBuilder.append(int).
Iterate digits in your int, and for each digit you can append(eachDigit) to the StringBuilder element. This will also reduce the complexity of intToString() to \ since you do not need to create a new
String instance each iteration. To get a String object from the StringBuilder, use StringBuilder.toString(). Or, if you are not allowed, you can use StringBuilder.subString(0).
You should also use a StringBuilder.append() (using the same idea) to reverse the resulting string (your second loop in your code).
Since it is not homework (as per comments), I have no problems providing a code snap. It should look something like this:
public static String intToString(int n) {
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
while (n > 0) {
int curr = n % 10;
n = n/10;
sb.append(curr);
}
String s = sb.substring(0);
sb = new StringBuilder();
for (int i = s.length() -1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.substring(0);
}
Notes:
- You can also use
StringBuilder.reverse()instead of the second loop. - In here, \
means linear in the the number of digits in the input number (
nis the number of digits in the input number - not the number itself!) If you are looking for the complexity in terms of the initial number (it is \) since you divide your element by 10 each iterations, you have a total of \
iterations for each loop, which results in \
.
For your example , I should point out some problems : first , when you add two add string frequently, you should use StringBuilder instead ; second , you should consider Integer.MIN_VALUE into account!Here is my code:
public static String parseInt(int integer)
{
boolean ifNegative = integer<0;
boolean ifMin = integer == Integer.MIN_VALUE;
StringBuilder builder = new StringBuilder();
integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer;
List<Integer> list = new LinkedList<Integer>();
int remaining = integer;
int currentDigit = 0 ;
while(true)
{
currentDigit = remaining%10;
list.add(currentDigit);
remaining /= 10;
if(remaining==0) break;
}
currentDigit = list.remove(0);
builder.append(ifMin?currentDigit+1:currentDigit);
for(int c : list)
builder.append(c);
builder.reverse().insert(0, ifNegative?'-':'+');
return builder.toString();
}
Videos
String myString = "1234";
int foo = Integer.parseInt(myString);
If you look at the Java documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which you can handle:
int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
foo = 0;
}
(This treatment defaults a malformed number to 0, but you can do something else if you like.)
Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:
import com.google.common.primitives.Ints;
int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)
For example, here are two ways:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
There is a slight difference between these methods:
valueOfreturns a new or cached instance ofjava.lang.IntegerparseIntreturns primitiveint.
The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.
Converting String to int without any library function
public static int stringToInt(String number) {
int res = 0;
for (int i = 0; i < number.length(); i++) {
res = res * 10 + number.charAt(i) - '0';
}
return res;
}
Perform whatever calculation you want to perform and then use the following method to convert the int back to String without any library function
Converting int to String without any library function
public static String parseInt(int integer)
{
boolean ifNegative = integer<0;
boolean ifMin = integer == Integer.MIN_VALUE;
StringBuilder builder = new StringBuilder();
integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer;
List<Integer> list = new LinkedList<Integer>();
int remaining = integer;
int currentDigit = 0 ;
while(true)
{
currentDigit = remaining%10;
list.add(currentDigit);
remaining /= 10;
if(remaining==0) break;
}
currentDigit = list.remove(0);
builder.append(ifMin?currentDigit+1:currentDigit);
for(int c : list)
builder.append(c);
builder.reverse().insert(0, ifNegative?'-':'+');
return builder.toString();
}
The source code for Integer.parseInt is available on GrepCode. It uses a package-private method to generate NumberFormatException errors, but you can leave those out and the code will still work for valid strings.
public static int parseInt(String s, int radix) {
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
}
i++;
}
multmin = limit / radix;
while (i < len) {
digit = Character.digit(s.charAt(i++), radix);
result *= radix;
result -= digit;
}
}
return negative ? result : -result;
}
here is a solution :
int tryParseInt(String value) {
try {
return Integer.parseInt(value);
} catch(NumberFormatException nfe) {
// Log exception.
return 0;
}
}
you should catch NumberFormatException instead of exception.
I'd consider using NumberUtils.toInt from Apache Commons Lang which does exactly this:
public static int NumberUtils.toInt(java.lang.String str, int defaultValue)
The implementation uses the already mentioned Integer.parseInt with an additional null check.
See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)
I'm creating a program of a "yes or no" quiz. At the end, the program is supposed to add up the number of yes and nos and give a result that corresponds to the total.
Example: If someone answered yes for all six questions, that would equal '6'. If someone answer yes four times and no twice, that would equal '4'.
I have the program looking pretty good. But I do have one problem that I can't figure out.
When a questioned is asked, the user types in 'yes' or 'no'. I need the yes to convert to 1 and the no to convert to 0 for the program to work.
I need a way to convert the user entry 'yes' or 'no' to '1' and '0', respectively.
Anyone know how to get this to work or point me in the right direction?
You could use a Scanner and call useDelimiter(String) to set your separator(s). Something like,
String str = "0000:0010:1111:3000\n" + "0003:0010:1113:3000\n"
+ "0004:0010:1188:3009";
Scanner sc = new Scanner(str);
sc.useDelimiter("[:|\\s]+"); // <-- one or more colon or whitespace
while (sc.hasNextInt()) {
System.out.printf("%04d%n", sc.nextInt()); // <-- format to 4 digits with
// leading zeros.
}
It's quite simple to parse int from char array, this is demo code:
public static int parseInt(char[] chars, int offset, int length) {
int r = 0;
for (int i = offset; i < offset + length; ++i) {
r *= 10;
r += chars[i] - '0';
}
return r;
}
You can add some security check for array length and make sure the char is really digits if you like.