Testing some java

As my first post, to test the layout and some plugins, I have decided to share a little Java class that converts a String input to an int. While it is not perfect, it seems to work well enough under the constraint of not using library functions to do the conversion.

When I wrote it I decided to just throw decimal point entry to the wayside. However, looking back at it I could have allowed it and either floored the value or only permitted whole number values.

Overall I think this implementation handles the problem statement without over-complicating matters.

public class StringToInt {

	public static int strToInt(String input) {
		int number = 0;
		int negFlag = 1;
		int count = 0;
		for (char s : input.toCharArray()) {
			if (s == '-') {
				if (count > 0) {
					throw new NumberFormatException();
				negFlag = -1;
			if (s < '0' || s > '9') {
				throw new NumberFormatException();
			number *= 10;
			number += (s - '0');
		return number * negFlag;
  1. count is never used, btw. so 12-12 will pass as 1212

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>