一亩三分地论坛

 找回密码
 获取更多干货,去instant注册!

扫码关注一亩三分地公众号
查看: 1218|回复: 11
收起左侧

[CS61B_Spring 2015] HW2

[复制链接] |试试Instant~ |关注本帖
hurricane_e 发表于 2015-6-2 13:05:36 | 显示全部楼层 |阅读模式

[其他]CS61B DATA STRUCTURE #14 - 2015-05-25@Berkeley

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看,没有帐号?获取更多干货,去instant注册!

x
RT~
karte_polo 发表于 2015-6-8 00:50:25 | 显示全部楼层
1. Calculator Tester.java


import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;


public class CalculatorTest {
    /* Do not change this to be private. For silly testing reasons it is public. */
    public Calculator tester;

    /**
     * setUp() performs setup work for your Calculator.  In short, we
     * initialize the appropriate Calculator for you to work with.
     * By default, we have set up the Staff Calculator for you to test your
     * tests.  To use your unit tests for your own implementation, comment
     * out the StaffCalculator() line and uncomment the Calculator() line.
     **/
    @Before
    public void setUp() {
        //tester = new StaffCalculator(); // Comment me out to test your Calculator
        tester = new Calculator();   // Un-comment me to test your Calculator
    }

    // TASK 1: WRITE JUNIT TESTS
    // YOUR CODE HERE
    @Test
    public void CalculatorTester() {
        assertEquals(3,tester.add(1, 2));
        assertEquals(8,tester.add(7, 1));
        assertEquals(25,tester.add(13, 12));
        assertEquals(0,tester.add(2, -2));
        assertEquals(7,tester.add(-11, 18));
        assertEquals(-2,tester.add(-1, -1));// end of all addition tests
        assertEquals(8,tester.multiply(4, 2));
        assertEquals(35,tester.multiply(5, 7));//end of multiplication tests
    }

    /* Run the unit tests in this file. */
    public static void main(String... args) {
        jh61b.junit.textui.runClasses(CalculatorTest.class);
    }      
}


2. Calculator.java  


import list.EquationList;

public class Calculator {
    // YOU MAY WISH TO ADD SOME FIELDS
        EquationList el;
        int hsize = 0;
    /**
     * TASK 2: ADDING WITH BIT OPERATIONS
     * add() is a method which computes the sum of two integers x and y using
     * only bitwise operators.
     * @param x is an integer which is one of two addends
     * @param y is an integer which is the other of the two addends
     * @return the sum of x and y
     **/
    public int add(int x, int y) {
            int bin_unchanged,bin_changed;
            bin_unchanged = x^y;
                bin_changed = (x&y)<<1;
            if (bin_changed == 0){
                    return bin_unchanged | bin_changed;
            }else{
                    return add(bin_unchanged,bin_changed);
            }
    }

    /**
     * TASK 3: MULTIPLYING WITH BIT OPERATIONS
     * multiply() is a method which computes the product of two integers x and
     * y using only bitwise operators.
     * @param x is an integer which is one of the two numbers to multiply
     * @param y is an integer which is the other of the two numbers to multiply
     * @return the product of x and y
     **/
    public int multiply(int x, int y) {
            int digit;
            if (y==1){
                    return x;
            }
            digit = y & 1;
            if (digit == 1){
                    return add(x,multiply(x<<1,y>>>1));
            }else{
                    return multiply(x<<1,y>>>1);
            }
        // YOUR CODE HERE
    }

    /**
     * TASK 5A: CALCULATOR HISTORY - IMPLEMENTING THE HISTORY DATA STRUCTURE
     * saveEquation() updates calculator history by storing the equation and
     * the corresponding result.
     * Note: You only need to save equations, not other commands.  See spec for
     * details.
     * @param equation is a String representation of the equation, ex. "1 + 2"
     * @param result is an integer corresponding to the result of the equation
     **/
    public void saveEquation(String equation, int result) {
        // YOUR CODE HERE
            if (el == null){
                    el = new EquationList(equation,result,null);
            }else{
                    el = new EquationList(equation,result,el);
            }
            hsize++;
    }

    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     * printAllHistory() prints each equation (and its corresponding result),
     * most recent equation first with one equation per line.  Please print in
     * the following format:
     * Ex   "1 + 2 = 3"
     **/
    public void printAllHistory() {
        // YOUR CODE HERE
            printHistory(hsize);
           
    }

    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     * printHistory() prints each equation (and its corresponding result),
     * most recent equation first with one equation per line.  A maximum of n
     * equations should be printed out.  Please print in the following format:
     * Ex   "1 + 2 = 3"
     **/
    public void printHistory(int n) {
        // YOUR CODE HERE
            EquationList l = el;
            int i = 0;
            while (i<n){
                    if (l==null){
                            System.out.println("Out of History Bounds! Printing stops here.");
                            break;
                    }
                    System.out.println(l.equation+" = "+l.result);
                    l = l.next;
                    i++;
            }
    }

    /**
     * TASK 6: CLEAR AND UNDO
     * undoEquation() removes the most recent equation we saved to our history.
    **/
    public void undoEquation() {
        // YOUR CODE HERE
            el = el.next;
            hsize--;
    }

    /**
     * TASK 6: CLEAR AND UNDO
     * clearHistory() removes all entries in our history.
     **/
    public void clearHistory() {
        // YOUR CODE HERE
            el = null;
            hsize = 0;
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     * cumulativeSum() computes the sum over the result of each equation in our
     * history.
     * @return the sum of all of the results in history
     **/
    public int cumulativeSum() {
        // YOUR CODE HERE
            int sum = 0;
            if (el!=null){
            EquationList p = el;
            while (p!=null){
                    sum+=p.result;
                    p = p.next;
               }
            }
        return sum;
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     * cumulativeProduct() computes the product over the result of each equation
     * in history.
     * @return the product of all of the results in history
     **/
    public int cumulativeProduct() {
            int product = 1;
            if (el!=null){
            EquationList p = el;
            while (p!=null){
                    product*=p.result;
                    p = p.next;
               }
            }
        return product;
    }
}


3. CalculatorUI.java


public class CalculatorUI {

        public static void main(String[] args) {
                int result;
                Calculator c = new Calculator();
        while (true) {
            System.out.print("> ");
            String input = StdIn.readString();
            switch (input){
            case"quit":return;
            case "history":
                int count = StdIn.readInt();
                c.printHistory(count);
                break;
            case "dump": c.printAllHistory(); break;
            case "undo": c.undoEquation(); break;
            case "clear": c.clearHistory(); break;
            case "sum": System.out.println(c.cumulativeSum()); break;
            case "product": System.out.println(c.cumulativeProduct()); break;
            default:
                    int a = Integer.parseInt(input);
                    StdIn.readChar();
                    String operator = StdIn.readString();
                    StdIn.readChar();
                    input = StdIn.readString();
                    if (input.equals("-") || input.lastIndexOf('-')>0){
                            System.out.println("Invalid input");
                            continue;
                    }
                    int b = Integer.parseInt(input);
                    if(operator.equals("+")){
                            result = c.add(a, b);
                    c.saveEquation(a + " + " + b, result);
                            System.out.println(result);
                    }else if(operator.equals("-")){
                            result = c.add(a, -b);
                    c.saveEquation(a + " - " + b, result);
                            System.out.println(result);
                    }else if(operator.equals("*")){
                            result = c.multiply(a, b);
                    c.saveEquation(a + " * " + b, result);
                            System.out.println(result);
                    }else{
                            System.out.println("Invalid operators");
                    }
            }
        }
        }
}

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

a0106660 发表于 2015-6-17 00:22:50 | 显示全部楼层
这个作业开始看来挺费劲的,因为不知道怎么把十进制变成二进制。。。后来写了程序了解了 Int 在java 里本来就是二进制,只不过以十进制显示。其实PPT 也是这样,之前没认真看。
我感觉我的做法粗暴了点,应该有更优美简单的做法,欢迎讨论分析更好的解法。test就不贴了,staffCalculator 测试 举个例子:(-2+3)错了。。。反正有 - 2 就错。。。
简单说下我的做法:
加法 1. 利用hint 里的提示 利用for 循环 和 getbit() 方法得到被加数每一个位的bit。利用真值表写出 sum(每个bit相加得到的和) 还有carry(进位) 与 xBit,yBit 的关系。然后判断sum, sum为1就将result 的相应bit 位设置为1;
乘法容易些,利用加法搞定。

我现在还有些疑惑:
对于写 CalculatorTest 测试StaffCalculator。 怎么才能比较全面的设置测试呢。虽然我找到了bug,但是保不齐还有其他很多bug 没找到。。。

下面是作业:
三个新的数据成员和一个构造函数;
   public EquationList eListHead;

    public EquationList eListTail;

    public int sizeEL;

    public Calculator(){
        eListHead = new EquationList("",0,null);
        eListTail = eListHead;
        sizeEL = 0;
    }


public int add(int x, int y) {
        // YOUR CODE HERE
        int carry = 0;
        int sum = 0;
        int result = 0;
        int xBit = 0;
        int yBit = 0;
        for (int i = 0;i < 32;i++){
            xBit = this.getBit(x,i);
            yBit = this.getBit(y,i);
            sum = xBit^yBit^carry;
            carry = (xBit&yBit)|(yBit&carry)|(xBit&carry);
            if(sum ==1){
                result = this.setBit(result,i);
            }
        }
        return result;
    }   

private int getBit(int x, int i){
        int ini = x;
        int position = i;
        int temp = 1;
        ini = ini>>>i;
        return temp&ini;
    }

    private int setBit(int x,int i){
        int ini = x;
        int position = i;
        int temp = 1;
        temp = temp<<i;
        return ini|temp;
    }


  public int multiply(int x, int y) {
        // YOUR CODE HERE
        int pEachBit = 0;
        int result = 0;
        for (int i =0;i<32 ;i++ ) {
            if(this.getBit(y,i)==1){
                pEachBit = x<<i;
                result = this.add(result,pEachBit);
            }
        }
        return result;
    }


public void saveEquation(String equation, int result) {
        // YOUR CODE HERE
        eListTail.next = new EquationList(equation,result,null);
        eListTail = eListTail.next;
        sizeEL ++;

    }


public void printAllHistory() {
        // YOUR CODE HERE
        EquationList temp = eListHead.next;
        while(temp!=null){
            System.out.println(temp.equation+" = "+temp.result);
            temp = temp.next;
        }

    }


public void printHistory(int n) {
        // YOUR CODE HERE
        EquationList temp = eListHead.next;
        for (int i = 0;i<sizeEL-n ; i++) {
            temp = temp.next;
        }
        System.out.println(temp.equation+" = "+temp.result);
    }   


public void undoEquation() {
        // YOUR CODE HERE
        EquationList temp = eListHead;
        while(temp.next!=eListTail){
            temp = temp.next;
        }
        eListTail = temp;
        eListTail.next = null;
        sizeEL--;
    }


public void clearHistory() {
        // YOUR CODE HERE
        eListHead = new EquationList("",0,null);
        eListTail = eListHead;
        sizeEL = 0;
    }


public int cumulativeSum() {
        // YOUR CODE HERE
        if(eListHead.next==null){
            return 0;
        }else{
            EquationList temp = eListHead.next;
            int sum = 0;
            while(temp!=null){
                sum = sum + temp.result;
                temp = temp.next;
            }
            return sum;
        }

  public int cumulativeProduct() {
        // YOUR CODE HERE
         if(eListHead.next==null){
            return 0;
        }else{
            EquationList temp = eListHead.next;
            int product = 1;
            while(temp!=null){
                product = product*temp.result;
                temp = temp.next;
            }
            return product;
        }
    }

    }





Calculator.PNG

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

a0106660 发表于 2015-6-17 00:35:26 | 显示全部楼层
一楼实现的方法很好啊。我还略作弊的用循环。循环里用了加法。。。  看来水平还是不够......
回复 支持 反对

使用道具 举报

西风吹草 发表于 2015-6-22 07:11:36 | 显示全部楼层
只做了加法和乘法两道题。。

2.
        public static int add(int x, int y){
                int temp = 0;
                int xtemp; int ytemp;
                int sumtemp = 0; int sum = 0;
                int digits = 0;
                while (x != 0 || y != 0){
                        xtemp = x & 1; ytemp = y & 1;
                        if (xtemp == 0 && ytemp == 0){
                                sumtemp = (sumtemp << 1) | temp;
                                temp = 0;
                        }else if (xtemp == 1 && ytemp == 1){
                                sumtemp = (sumtemp << 1) | temp;
                                temp = 1;
                        }else{
                                if (temp == 0){
                                        sumtemp = (sumtemp << 1) | 1;
                                        temp = 0;
                                }else{
                                        sumtemp = (sumtemp << 1) | 0;
                                        temp = 1;
                                }
                        }
                        x = x >>> 1; y = y >>> 1;
                        digits += 1;
                }
                if (temp == 1){
                        sumtemp = (sumtemp << 1) | 1;
                        digits += 1;
                }
                while (digits > 0){
                        sum = (sum << 1) | (sumtemp & 1);
                        sumtemp = sumtemp >>> 1;
                        digits -= 1;
                }
                return sum;
        }

3.
        public static int multiply(int x, int y){
                if (x == 0 || y == 0){
                        return 0;
                }
                int product = 0;
                int ydigits = 0;
                while (y != 0){
                        if ((y & 1) == 1){
                                product = add(product, x << ydigits);
                        }
                        y = y >>> 1;
                        ydigits += 1;
                }
                return product;
        }

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

whosays 发表于 2015-6-24 11:57:10 | 显示全部楼层
a0106660 发表于 2015-6-17 00:22
这个作业开始看来挺费劲的,因为不知道怎么把十进制变成二进制。。。后来写了程序了解了 Int 在java 里本来 ...

想请教下你怎么贴图的。。。谢谢
回复 支持 反对

使用道具 举报

whosays 发表于 2015-6-24 11:59:17 | 显示全部楼层

代码如下,计算器运行结果正在找寻贴图方法再来补。。。
public class Calculator {
    // YOU MAY WISH TO ADD SOME FIELDS
    EquationList elist = new EquationList("", 0, null);
    int elSize = 0;

    /**
     * TASK 2: ADDING WITH BIT OPERATIONS
     **/

    public int add(int x, int y) {
        // YOUR CODE HERE
        int sum = x ^ y; // + without carry 0+0=0, 0+1=1+0=1, 1+1=0
        int carry = (x & y) << 1; // 1+1=2
        if (carry != 0) {
            return add(sum, carry);
        }
        return sum;
    }

    /**
     * TASK 3: MULTIPLYING WITH BIT OPERATIONS
     **/
    public int multiply(int x, int y) {
        // YOUR CODE HERE
        int product = 0;
        while (y != 0) {
            if ((y & 1) != 0) {
                product = product + x;
            } // close if
            x <<= 1;
            y >>>= 1;
        }
        return product;
    }

    /**
     * TASK 5A: CALCULATOR HISTORY - IMPLEMENTING THE HISTORY DATA STRUCTURE
     **/
    // public EquationList(String equation, int result, EquationList next)
    public void saveEquation(String equation, int result) {
        // YOUR CODE HERE
        elist = new EquationList(equation, result, elist);
        elSize += 1;
    }

    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     **/
    public void printAllHistory() {
        // YOUR CODE HERE
        printHistory(elSize);
    }

    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     **/
    public void printHistory(int n) {
        // YOUR CODE HERE
        EquationList l = elist;
        while (n > 0) {
            System.out.println(l.equation + " = " + l.result);
            l = l.next;   
            n -= 1;
        } // close while
    }   

    /**
     * TASK 6: CLEAR AND UNDO
    **/
    public void undoEquation() {
        // YOUR CODE HERE
        if (elist.next != null) {
            elist = elist.next;
            elSize -= 1;
        }
    }

    /**
     * TASK 6: CLEAR AND UNDO
     * clearHistory() removes all entries in our history.
     **/
    public void clearHistory() {
        // YOUR CODE HERE
        elist = null;
        elSize = 0;
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     * cumulativeSum() computes the sum over the result of each equation in our
     * history.
     * @return the sum of all of the results in history
     **/
    public int cumulativeSum() {
        // YOUR CODE HERE
        EquationList l = elist;
        int sum = 0;
        int k = elSize;
        while (k > 0){
            sum += l.result;
            k -= 1;
            l = l.next;
        }     
        return sum;
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     **/
    public int cumulativeProduct() {
        // YOUR CODE HERE
        EquationList l = elist;
        int product = 1;
        int k = elSize;
        while (k > 0) {
            product *= l.result;
            k -= 1;
            l = l.next;
        }
        return product;
    }
}

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

a0106660 发表于 2015-6-24 12:00:15 | 显示全部楼层
whosays 发表于 2015-6-24 11:57
想请教下你怎么贴图的。。。谢谢

点文本框右上角的高级回复模式,里面有上传图片
回复 支持 反对

使用道具 举报

whosays 发表于 2015-6-24 23:28:09 | 显示全部楼层
a0106660 发表于 2015-6-24 12:00
点文本框右上角的高级回复模式,里面有上传图片

啊……谢谢
回复 支持 反对

使用道具 举报

whosays 发表于 2015-6-24 23:39:20 | 显示全部楼层
不知道为啥传图总被吞,只好粘贴运行结果了。。。
xxxxxxx$: java StaffCalculatorUI
> 1 + 2
3
> 4 * 9
36
> -6 * 9
-54
> dump
-6 * 9 = -54
4 * 9 = 36
1 + 2 = 3
> sum
-15
> product
-5832
> undo
> dump
4 * 9 = 36
1 + 2 = 3
> clear
> dump
> quit
xxxxxxxxxxx$

回复 支持 反对

使用道具 举报

Casualet 发表于 2015-7-18 22:21:58 | 显示全部楼层
CalculatorTest.java
/*
刚开始没想法,跳过了;后来自己写加法的的时候想到了用正数和负数测试,解决。
*/
public class CalculatorTest {
    /* Do not change this to be private. For silly testing reasons it is public. */
    public Calculator tester;

    /**
     * setUp() performs setup work for your Calculator.  In short, we
     * initialize the appropriate Calculator for you to work with.
     * By default, we have set up the Staff Calculator for you to test your
     * tests.  To use your unit tests for your own implementation, comment
     * out the StaffCalculator() line and uncomment the Calculator() line.
     **/
    @Before
    public void setUp() {
//        tester = new StaffCalculator(); // Comment me out to test your Calculator
         tester = new Calculator();   // Un-comment me to test your Calculator
    }

    // TASK 1: WRITE JUNIT TESTS
    // YOUR CODE HERE
    @Test
    public void testAdd(){
       int value;
       value=tester.add(5,7);
       assertEquals(12,value);

       value=tester.add(-5,7);
       assertEquals(2,value);
   
       value=tester.add(5,-7);
       assertEquals(-2,value);
  
       value=tester.add(-5,-7);
       assertEquals(-12,value);

       value= tester.add(value,-10);              
       assertEquals(-22,value);

       value=tester.add(10000,10000);
       assertEquals(20000,value);

    }
    @Test
    public void testMul(){
       int value;
       value=tester.multiply(2,2);
       assertEquals(4,value);
       value=tester.multiply(-2,-2);
       assertEquals(4,value);
       value=tester.multiply(2,-2);
       assertEquals(-4,value);
       value=tester.multiply(2,-2);
       assertEquals(-4,value);     

    }

    /* Run the unit tests in this file. */
    public static void main(String... args) {
        jh61b.junit.textui.runClasses(CalculatorTest.class);
    }      
}

Calculator.java
/*
想到了用真值表来实现,其他部分为链表的操作。
*/

import list.EquationList;//this is how to import !!!
public class Calculator {
    // YOU MAY WISH TO ADD SOME FIELDS
    EquationList historyHead;   
   
    public Calculator(){
        this.historyHead=new EquationList(null,-1,null);

    }

    public class record{
      public EquationList cur;
      public record pre;
    }



    /**
     * TASK 2: ADDING WITH BIT OPERATIONS
     * add() is a method which computes the sum of two integers x and y using
     * only bitwise operators.
     * @param x is an integer which is one of two addends
     * @param y is an integer which is the other of the two addends
     * @return the sum of x and y
     **/
    public int add(int x, int y) {
        // YOUR CODE HERE
        int result=0;
        int add=0;
        int xBit,yBit,curBit;
        for(int i=0;i<=31;i++){
           xBit=this.getBit(x,i);
           yBit=this.getBit(y,i);
        //   if(xBit==-1||yBit==-1) System.out.println(".......");
  
           curBit=this.truth(xBit,yBit,add);
        //   if(curBit==-1) System.out.println("error");               

           add=curBit>>1;
           curBit=curBit&1;

           result=result|(curBit<<i);
        }
        return result;
    }
    int n=0;
    public int truth(int a1,int a2,int add){
      n++;
//      System.out.println(""+n+"a1: "+a1+" a2: "+a2+" add: "+add);
      if(a1==0&&a2==0&&add==0)
          return 0;
      if(a1==0&&a2==0&&add==1)
          return 1;
      if(a1==0&&a2==1&&add==0)
          return 1;
      if(a1==0&&a2==1&&add==1)
          return 2;
      if(a1==1&&a2==0&&add==0)
          return 1;
      if(a1==1&&a2==0&&add==1)
          return 2;
      if(a1==1&&a2==1&&add==0)
          return 2;
      if(a1==1&&a2==1&&add==1)
          return 3;

      return -1;//this is helpful, java ensures that the method do has a return value
    }

    public int getBit(int x, int index){
          int i=1;
          return (x&(i<<index))>>>index;//a single bit and an int num are not identical!!!
    }




    /**
     * TASK 3: MULTIPLYING WITH BIT OPERATIONS
     * multiply() is a method which computes the product of two integers x and
     * y using only bitwise operators.
     * @param x is an integer which is one of the two numbers to multiply
     * @param y is an integer which is the other of the two numbers to multiply
     * @return the product of x and y
     **/
    public int multiply(int x, int y) {
        // YOUR CODE HERE
        int result=0;
        int modifier;
        if(x==0||y==0) return 0;

        if(x<0&&y<0){
             x=-x;
             y=-y;//is this operation allowed?
             modifier=0;
         }else if(x<0&&y>0){
            x=-x;
            modifier=1;
         }else if(x>0&&y<0){
           y=-y;
           modifier=1;
         }else{
           modifier=0;
         }         
         int t;   
        for(int i=0;i<=31;i++){
            t=(y>>i)&1;
            if(t==0) continue;  
            result=this.add(x<<i,result);
        }

        return modifier==0?result:-result;
    }

    /**
     * TASK 5A: CALCULATOR HISTORY - IMPLEMENTING THE HISTORY DATA STRUCTURE
     * saveEquation() updates calculator history by storing the equation and
     * the corresponding result.
     * Note: You only need to save equations, not other commands.  See spec for
     * details.
     * @param equation is a String representation of the equation, ex. "1 + 2"
     * @param result is an integer corresponding to the result of the equation
     **/
    public void saveEquation(String equation, int result) {
        // YOUR CODE HERE
        EquationList tempHis=this.historyHead;
        while(historyHead.next!=null){
             historyHead=historyHead.next;
        }
        EquationList temp=new EquationList(equation,result,null);
        historyHead.next=temp;
        this.historyHead=tempHis;
        //System.out.println(this.historyHead.equation)  
//        printList();
    }
   
    public void printList(){

        System.out.println("now its time to print out the equation list");
        EquationList pr=this.historyHead;
        while(pr.next!=null){
            System.out.println(pr.equation);
            pr=pr.next;
        }

    }
//when traversing a list, remember to add xx=xx.next. or you will have
//infinite loop

    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     * printAllHistory() prints each equation (and its corresponding result),
     * most recent equation first with one equation per line.  Please print in
     * the following format:
     * Ex   "1 + 2 = 3"
     **/
    public void printAllHistory() {
        // YOUR CODE HERE
        int count=0;
        EquationList temp=this.historyHead;
        while(temp.next!=null){
           count++;
           temp=temp.next;
        }
        printHistory(count);
      
    }
// how to write printAllHistory in an recursive way??
    /**
     * TASK 5B: CALCULATOR HISTORY - PRINT HISTORY HELPER METHODS
     * printHistory() prints each equation (and its corresponding result),
     * most recent equation first with one equation per line.  A maximum of n
     * equations should be printed out.  Please print in the following format:
     * Ex   "1 + 2 = 3"
     **/
    public void printHistory(int n) {//how to reversely print items in a single linked list?
        // YOUR CODE HERE
        EquationList temp=this.historyHead;
        record re;
        record rTemp=new record();
        record rrTemp;
        rTemp.pre=null;
        rTemp.cur=this.historyHead;
        while(historyHead.next!=null){                 
             historyHead=historyHead.next;
             rrTemp=new record();
             rrTemp.pre=rTemp;
             rrTemp.cur=historyHead;
             rTemp=rrTemp;
        }
      
       // System.out.println(historyHead.equation+'='+historyHead.result);
        int count=0;
        while(rTemp.pre!=null&&count<n){
             historyHead=rTemp.cur;
             System.out.println(historyHead.equation+'='+historyHead.result);
             rTemp=rTemp.pre;
             count++;
        }  
        this.historyHead=temp;
    }   

    /**
     * TASK 6: CLEAR AND UNDO
     * undoEquation() removes the most recent equation we saved to our history.
    **/
    public void undoEquation() {
        // YOUR CODE HERE
       EquationList temp=this.historyHead;
       while(temp.next.next!=null){
           temp=temp.next;
        }
        temp.next=null;

    }

    /**
     * TASK 6: CLEAR AND UNDO
     * clearHistory() removes all entries in our history.
     **/
    public void clearHistory() {
        // YOUR CODE HERE
        this.historyHead=new EquationList(null,-1,null);
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     * cumulativeSum() computes the sum over the result of each equation in our
     * history.
     * @return the sum of all of the results in history
     **/
    public int cumulativeSum() {
        // YOUR CODE HERE
        EquationList temp=this.historyHead.next;
        int result=0;
        while(temp!=null){
            result+=temp.result;
            temp=temp.next;
        }

        return result;
    }

    /**
     * TASK 7: ADVANCED CALCULATOR HISTORY COMMANDS
     * cumulativeProduct() computes the product over the result of each equation
     * in history.
     * @return the product of all of the results in history
     **/
    public int cumulativeProduct() {
        // YOUR CODE HERE
        EquationList temp=this.historyHead.next;
        int result=1;
        while(temp!=null){//remember to differeciate between temp!=null and
                          //temp.next!=null, when used as test condition
          result*=temp.result;
          temp=temp.next;
        }
        return result;
    }
}
Calculator.java
public class CalculatorUI{
   public static void main(String[] args){
         String first;
         Calculator tester=new Calculator();
         while(true){
           System.out.println(">");
           first=StdIn.readString();
        switch(first){
        case "quit": break;
        case "history":{
              int n=StdIn.readInt();
              tester. printHistory(n);                        
              break;
          }
        case "dump":{
             tester.printAllHistory();
             break;
         }
        case "undo":{
            tester.undoEquation();
            break;
        }
        case "clear":{
            tester.clearHistory();
            break;
       }
        case "sum":{
            int re=tester.cumulativeSum();
            System.out.println(re);
            break;
        }
        case "product":{
            int re=tester.cumulativeProduct();
            System.out.println(re);
            break;//always remember to break;
        }
        default:{
           int n1=Integer.parseInt(first);
           int result;
           String operation=StdIn.readString();//not char
           int n2=StdIn.readInt();
           if(operation.equals("+")){
              result=tester.add(n1,n2);
              tester.saveEquation(n1+" + "+n2,result);
           }
          else if(operation.equals("*")){
              result=tester.multiply(n1,n2);
              tester.saveEquation(n1+" * "+n2,result);
           }else{

              result=-7;

           }
           System.out.println(result);
        }
        }
      }
   }
}

/*
工作空隙时间写了好久。。。如果这是基础入门课,那我肯定挂科了=_=
*/

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

HNAKXR 发表于 2016-1-30 17:23:40 | 显示全部楼层
位运算来写加法和乘法不容易,加法还好,乘法涉及负数有时出错,找不出问题,没办法只能先当成正数算再考虑符号。
hw2_1.jpeg
hw2_2.jpeg
hw2_3.jpeg
hw2_4.jpeg
hw2_5.jpeg

最后一个task传不上图了(只能5张):
***-MacBook-Pro:hw2 ***$ java StaffCalculatorUI
> 1 + -5
-4
> 3 * -7
-21
> 5 + 8
13
> -4 * 16
-64
> sum
-76
> product
-69888
>

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

本版积分规则

请点这里访问我们的新网站:一亩三分地Instant.

Instant搜索更强大,不扣积分,内容组织的更好更整洁!目前仍在beta版本,努力完善中!反馈请点这里

关闭

一亩三分地推荐上一条 /5 下一条

手机版|小黑屋|一亩三分地论坛声明 ( 沪ICP备11015994号 )

custom counter

GMT+8, 2016-12-11 08:56

Powered by Discuz! X3

© 2001-2013 Comsenz Inc. Design By HUXTeam

快速回复 返回顶部 返回列表