Advertisement
alexarcan

SVV_lab1

Sep 28th, 2016
329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. import static org.junit.Assert.*;
  2.  
  3. import java.nio.BufferOverflowException;
  4.  
  5. import org.junit.Test;
  6.  
  7. public class StringConv {
  8. public int strToInt(String str) throws NumberFormatException, BufferOverflowException {
  9. double sum=0;
  10.  
  11. boolean negative = false;
  12. if(str == null || str.isEmpty())
  13. throw new NumberFormatException();
  14. if(str.charAt(0) == '-')
  15. negative = true;
  16. int digit;
  17. for (int i = 0; i < str.length(); i++) {
  18.  
  19. if(Character.isLetter(str.charAt(i)))
  20. throw new NumberFormatException();
  21. if(negative == true && i == str.length()-1)
  22. continue;
  23. else
  24. digit = (int)str.charAt(str.length()-i-1) - (int)'0';
  25. sum = sum + digit * (int)Math.pow(10, i);
  26. }
  27.  
  28. if(negative == true)
  29. sum = sum * (-1);
  30.  
  31. if(Double.compare(sum, new Double(Integer.MAX_VALUE)) == 1)
  32. throw new BufferOverflowException();
  33.  
  34. return (int)sum;
  35. }
  36.  
  37. @Test(expected=NumberFormatException.class)
  38. public void testStringFormat()
  39. {
  40. strToInt("ab");
  41. }
  42.  
  43. @Test
  44. public void testSingleDigit()
  45. {
  46. assertEquals("Single Digit Test", 5, strToInt("5"));
  47. }
  48.  
  49. @Test
  50. public void testString()
  51. {
  52. assertEquals("String Test", 12, strToInt("12"));
  53. }
  54.  
  55. @Test
  56. public void testNegative()
  57. {
  58. assertEquals("Negative Test", -20, strToInt("-20"));
  59. }
  60.  
  61.  
  62. @Test(expected=NumberFormatException.class)
  63. public void testNull()
  64. {
  65. strToInt(null);
  66. }
  67.  
  68. @Test(expected=NumberFormatException.class)
  69. public void testEmpty()
  70. {
  71. strToInt("");
  72. }
  73.  
  74. @Test(expected=BufferOverflowException.class)
  75. public void testBigNumber()
  76. {
  77. strToInt("1234567891");
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement