Advertisement
jaVer404

level19.lesson08.task04(done) 1st attempt

Feb 22nd, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.77 KB | None | 0 0
  1. package com.javarush.test.level19.lesson08.task04;
  2.  
  3. /* Решаем пример
  4. В методе main подмените объект System.out написанной вами ридер-оберткой по аналогии с лекцией
  5. Ваша ридер-обертка должна выводить на консоль решенный пример
  6. Вызовите готовый метод printSomething(), воспользуйтесь testString
  7. Верните переменной System.out первоначальный поток
  8.  
  9. Возможные операции: + - *
  10. Шаблон входных данных и вывода: a [знак] b = c
  11. Отрицательных и дробных чисел, унарных операторов - нет.
  12.  
  13. Пример вывода:
  14. 3 + 6 = 9
  15. */
  16.  
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.PrintStream;
  19.  
  20. public class Solution {
  21.     public static TestString testString = new TestString();
  22.  
  23.     public static void main(String[] args) {
  24.         PrintStream originalOut = System.out;//сохраняем оригинальный System.out
  25.         ByteArrayOutputStream bAOS = new ByteArrayOutputStream();//создаем динам. массив
  26.         PrintStream stream = new PrintStream(bAOS);//создаем адаптер к классу PrintStream
  27.         System.setOut(stream);//устанавливаем адаптер как текущий out
  28.         //теперь печатает в bAOS
  29.         testString.printSomething();//out добавляет строки в bAOS
  30.         String origString = bAOS.toString();
  31.         String result[] = origString.split(" ");
  32.         int firstNum = Integer.parseInt(result[0]);
  33.         int secondNum = Integer.parseInt(result[2]);
  34.         int finaly;
  35.         if (result[1].equals("+")) {
  36.             finaly=firstNum+secondNum;
  37.             origString = origString+finaly;
  38.             origString = origString.replace("\n", "").replace("\r","");
  39.         }
  40.         else if (result[1].equals("-")) {
  41.             finaly = firstNum-secondNum;
  42.             origString = origString+finaly;
  43.             origString = origString.replace("\n", "").replace("\r","");
  44.         }
  45.         else if (result[1].equals("*")) {
  46.             finaly = firstNum*secondNum;
  47.             origString = origString+finaly;
  48.             origString = origString.replace("\n", "").replace("\r","");
  49.         }
  50.  
  51.         System.setOut(originalOut);//возвращаем оригинальный out (на консоль)
  52.         System.out.println(origString);//выводим в консоль (то, что result получил из bAOS)
  53.     }
  54.     public static class TestString {
  55.         public void printSomething() {
  56.             System.out.println("3 + 6 = ");
  57.         }
  58.     }
  59.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement