Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import static org.junit.Assert.*;
- import java.nio.BufferOverflowException;
- import org.junit.Test;
- public class StringConv {
- public int strToInt(String str) throws NumberFormatException, BufferOverflowException {
- double sum=0;
- boolean negative = false;
- if(str == null || str.isEmpty())
- throw new NumberFormatException();
- if(str.charAt(0) == '-')
- negative = true;
- int digit;
- for (int i = 0; i < str.length(); i++) {
- if(Character.isLetter(str.charAt(i)))
- throw new NumberFormatException();
- if(negative == true && i == str.length()-1)
- continue;
- else
- digit = (int)str.charAt(str.length()-i-1) - (int)'0';
- sum = sum + digit * (int)Math.pow(10, i);
- }
- if(negative == true)
- sum = sum * (-1);
- if(Double.compare(sum, new Double(Integer.MAX_VALUE)) == 1)
- throw new BufferOverflowException();
- return (int)sum;
- }
- @Test(expected=NumberFormatException.class)
- public void testStringFormat()
- {
- strToInt("ab");
- }
- @Test
- public void testSingleDigit()
- {
- assertEquals("Single Digit Test", 5, strToInt("5"));
- }
- @Test
- public void testString()
- {
- assertEquals("String Test", 12, strToInt("12"));
- }
- @Test
- public void testNegative()
- {
- assertEquals("Negative Test", -20, strToInt("-20"));
- }
- @Test(expected=NumberFormatException.class)
- public void testNull()
- {
- strToInt(null);
- }
- @Test(expected=NumberFormatException.class)
- public void testEmpty()
- {
- strToInt("");
- }
- @Test(expected=BufferOverflowException.class)
- public void testBigNumber()
- {
- strToInt("1234567891");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement