Программа блокировки комбинации с toString, getSolution и equals (ComboLock другой) - PullRequest
0 голосов
/ 15 апреля 2020
 I have a combination lock program and a combination lock tester.  Would anyone know how to develop a toString, getSolution, and equals(ComboLock another)?  The combination is rt 15, lt 28, rt 4. I tried to do 5 attempts and the last attempt seemed to work.

Алгоритм: * 1. Создайте класс ComboLock. * 2. Попытайтесь открыть его. * 3. Создайте второй ComboLock и сравните. *
* Описание проблемы: * * Это расширенная версия проблемы P8.1 в учебнике: * * Объявите класс ComboLock, который работает как кодовый замок в школьном или спортивном * шкафчике, как показано здесь. Кодовый замок * * Замок создается с номерами комбинированного набора от 0 до 39. * * Конструктор устанавливает три «секретных» номера и текущую позицию на 0. * Метод сброса сбрасывает набор так, чтобы он указывал на 0 * Методы turnLeft и turnRight поворачивают циферблат на заданное количество тиков * влево или вправо. * Метод open пытается открыть замок. Блокировка открывается, если пользователь сначала * повернул ее вправо на первый номер в комбинации, затем налево на * секунду и затем вправо на третий. Если замок не открывается, замок * сбрасывается. * Метод toString должен показывать текущую позицию циферблата замка. * Метод getSolution должен возвращать строку с тремя «секретными» числами *, разделенными пробелами. * Метод equals должен сравнивать три «секретных» числа двух замков (один * вызывающий объект, другой объект ComboLock параметра). *

Программа:

/**
 * Write a description of class ComboLock here.
 *
 * @author Quang Pham
 * @version Lab10-ClassDefinitions(ComboLock) 4/15/20
 * 
 *  Algorithm:
 *  1. Create a class ComboLock.
 *  2. Attempt to open it.
 *  3. Create a second ComboLock and compare.
 *  
 *  Problem Description:
 *
 * This is an enhanced version of problem P8.1 in the textbook:
 *
 * Declare a class ComboLock that works like the combination lock in a school or gym
 * locker, as shown here.   A combination lock
 *
 * The lock is constructed with a combination dial numbers between 0 and 39.
 *
 *    The constructor sets the three "secret" numbers and the current position to 0.
 *    The reset method resets the dial so that it points to 0.
 *    The turnLeft and turnRight methods turn the dial by a given number of ticks to
 *      the left or right.
 *    The open method attempts to open the lock. The lock opens if the user first
 *      turned it right to the first number in the combination, then left to the
 *      second, and then right to the third. If the lock doesn't open, the lock is 
 *      reset.
 *    The toString method should show current position of the lock's dial.
 *    The getSolution method should return a String with the three "secret" numbers 
 *      separated by spaces.
 *    The equals method should compare the three "secret" numbers of two locks (one
 *      the calling object, the other a parameter ComboLock object).
 *
 *  Here are the headings of the methods that should be included in your ComboLock class 
 *      for this lab:
 *
 *  public class ComboLock {
 *     . . .
 *     public ComboLock(int secret1, int secret2, int secret3) { ... }
 *     public void reset() { ... }
 *     public void turnLeft(int ticks) { ... }
 *     public void turnRight(int ticks) { ... }
 *           public boolean open() { ... }
 *     public String toString() { ... }
 *     public String getSolution() { ... }
 *     public boolean equals(ComboLock another){ ... }
 *  }  
 *
 * You will need to determine the properties required to track the state of a
 *   ComboLock and how close a combination is to opening the lock.
 * 
 * Please remember to document your constants and methods using Javadoc-style
 *   comments and tags. Spend some time making your documentation useful, thorough,
 *   and easy to understand.
 *
 * In a separate class, create a main method to test your class. Initialize a new
 *   ComboLock with combination 15 - 28 - 4. Demonstrate your ComboLock class by
 *   showing the results  of the following attempts to open the lock:
 *
 *    right 14, left 20 (33 ticks), right 4 (23 ticks)
 *    left 15, right 28, left 4
 *    right 15, left 28, right 8
 *    right 15, left 28
 *    right 15, left 28, left 4 (the correct combination)
 *
 * Create another ComboLock object with a combination of your choice and demonstrate
 *   how it works, as well.
 *
 * Finally compare the two locks using the equals method.
 *
 * Submit your Java program plus print screens or snips showing the results of
 *   trying to open your two ComboLock objects.
 *
 * Also submit a print screen or screens or snips showing the resulting Javadoc, 
 *   including the documentation for all methods.
 *
 * */
public class QuangComboLock {
    private int secret1 ;
    private int secret2 ;
    private int secret3 ;

    private boolean position0 = true ;
    private boolean position1, position2, position3 = false ;
    private int currentNumber = 0 ;
    private boolean validSoFar = false ;

    /**
     * Initializes the combination of the lock.
     * @param secret1  first number to turn right to
     * @param secret2  second number to turn left to
     * @param secret3  third number to turn right to
     */
    public QuangComboLock(int secret1, int secret2, int secret3) 
    { 
        this.secret1 = secret1 ;
        this.secret2 = secret2 ;
        this.secret3 = secret3 ;
    }

    /**
     * Resets the state of the lock so that it can be opened again.
     */
    public void reset() 
    { 
        position0 = true ;
        position1 = false ;
        position2 = false ;
        position3 = false ;
        validSoFar = true ;
    }

    /**
     * Turns lock right given number of ticks
     * @param ticks  number of ticks to turn right
     */
    public void turnRight(int ticks) 
    {
        if (position0)
        {
            currentNumber = ticks;
            if (currentNumber == secret1)
            {
                position1 = true;
                position0 = false;
            }
        }   
        if (position2 == true)
        {
            currentNumber = ticks;
            if (currentNumber == secret3)
            {
                position3 = true;
            } else 
            {
                position3 = false;
            }
        }
    }

    /**
     * Turns lock left given number of ticks
     * @param ticks  number of ticks to turn left
     */
    public void turnLeft(int ticks)
    { 
        if (position1 == true)
        {
            currentNumber = ticks ;
            if (currentNumber == secret2)
            {
                position2 = true ;
            }
            else
            {
                position2 = false ;

            }
        }
    }

    /**
     * Returns true if the lock can be opened now
     * @return true if lock is in open state
     */
     public boolean open() 
        {
            if (position1 && position2 && position3)
            {
                validSoFar = true ;
            }
            return validSoFar ;
        }

        //public void String toString()
        { 
            //TODO
        }

        //public void String getSolution()
        { 
            //TODO
        }

        //public boolean equals(ComboLock another)
        {
            //TODO
        }
    } 

import java.util.Scanner;
/**
 * Write a description of class SOComboLockTest here.
 *
 * @author Quang Pham
 * @version 4/15/20
 */
public class QuangComboLockTester {

    public static void main(String[] args) {
        // Random randomizer = new Random();

        int secret1 = 15;// randomizer.nextInt(40);
        int secret2 = 28;// randomizer.nextInt(40);
        int secret3 = 4;// randomizer.nextInt(40);

        QuangComboLock lock = new QuangComboLock(secret1, secret2, secret3);

        Scanner in = new Scanner(System.in);
        boolean opened = false;
        boolean turningRight = true;
        while (!opened) {
            System.out.println("Enter number of ticks to turn to the " + (turningRight ? "right" : "left")
                    + " 0 - 39. Enter an invalid number to quit.");
            int ticks = in.nextInt();
            if ((ticks < 0) || (ticks > 39)) {
                System.out.println("Invalid entry. The program will now exit.");
                return;
            }
            if (turningRight) {
                lock.turnRight(ticks);
                turningRight = !turningRight;
            }

            else {
                lock.turnLeft(ticks);
                turningRight = !turningRight;
            }
            opened = lock.open();
        }
        System.out.println("You opened the lock!");
    }

    //@Test
    public void test1() {
        QuangComboLock c = new QuangComboLock(14, 20, 4);
        c.turnRight(14);
        c.turnLeft(20);
        c.turnRight(4);
        //assertTrue("Should open but not", c.open());
    }

    //@Test
    public void test2() {
        QuangComboLock c = new QuangComboLock(15, 28, 4);
        c.turnLeft(15);
        c.turnRight(28);
        c.turnLeft(4);
        //assertTrue("Should open but not", c.open());
    }

    //@Test
    public void test3() {
        QuangComboLock c = new QuangComboLock(15, 28, 8);
        c.turnRight(15);
        c.turnLeft(28);
        c.turnRight(8);
        //assertTrue("Should open but not", c.open());
    }

    //@Test
    public void test4() {
        QuangComboLock c = new QuangComboLock(15, 28, 0);
        c.turnRight(15);
        c.turnLeft(28);
        c.turnRight(0);
        //assertFalse("Should not open but did", c.open());
    }

    //@Test
    public void test5() {
        QuangComboLock c = new QuangComboLock(15, 28, 4);
        c.turnRight(15);
        c.turnLeft(28);
        c.turnRight(4);
        //assertTrue("Should open and did", c.open());
    }
}

1 Ответ

0 голосов
/ 17 апреля 2020

В ComboLockTester я не знал, как проверить блокировку 5 раз.

Вот что у меня есть:

import java.util.Scanner;

/**
 * QuangComboLockTester assigns a combination to the lock and allows the user to enter the
 * combination numbers.  The position of the dial, the secret combination, and the lock is
 * compared to another lock.  Test the lock 5 times with different combinations.
 *
 * @author Quang Pham
 * @@version Lab10-ClassDefinitions(ComboLock) 4/22/20
 */
public class QuangComboLockTester {
    public static void main(String[] args) {
        // Random randomizer = new Random();

        int secret1 = 15;// randomizer.nextInt(40);
        int secret2 = 28;// randomizer.nextInt(40);
        int secret3 = 4;// randomizer.nextInt(40);

        QuangComboLock lock = new QuangComboLock(secret1, secret2, secret3);

        Scanner in = new Scanner(System.in);
        boolean opened = false;
        boolean turningRight = true;
        while (!opened) {
            System.out.println("Enter number of ticks to turn to the " + (turningRight ? "right" 
                    : "left")
                    + " 0 - 39. Enter an invalid number to quit.");
            int ticks = in.nextInt();
            if ((ticks < 0) || (ticks > 39)) {
                System.out.println("Invalid entry. The program will now exit.");
                return;
            }
            if (turningRight) {
                lock.turnRight(ticks);
                turningRight = !turningRight;
            } else {
                lock.turnLeft(ticks);
                turningRight = !turningRight;
            }
            opened = lock.open();
        }
        /**
         * Congratulates user for opening the lock.  Reports the current number,
         * reveals the secret combination, and compares one lock to another.
         */
        System.out.println("Congratulations!  You opened the lock!");
        System.out.println("Lock is at this current number:  " + lock.toString());
        System.out.println("The solution to the lock is:  " + lock.getSolution());
        QuangComboLock c = new QuangComboLock(23, 32, 13);
        System.out.println("QuangComboLock is equal to new QuangComboLock?" + lock.equals(lock));
        System.out.println(lock.test1(), lock.test2(), lock.test3(), lock.test4(), lock.test5());
    }

    //@Test
    public static test1() {
        QuangComboLock c = new QuangComboLock(15, 28, 4);
        c.turnRight(15);
        c.turnLeft(28);
        c.turnRight(4);
        return c.open() //assertTrue("Should open", c.open());
    }

    //@Test
    public static void test2() {
        QuangComboLock c = new QuangComboLock(15, 28, 4);
        c.turnLeft(15);
        c.turnRight(28);
        c.turnLeft(4);
        //assertFalse("Should not open", c.open()); 
    }

    //@Test
    public static void test3() {
        QuangComboLock c = new QuangComboLock(15, 28, 4);
        c.turnRight(15);
        c.turnLeft(28);
        c.turnRight(8);
        //assertFalse("Should not open", c.open());
    }

    //@Test
    public static void test4() {
        QuangComboLock c = new QuangComboLock(15, 28, 4);
        c.turnRight(15);
        c.turnLeft(28);
        c.turnRight(0);
        //assertFalse("Should not open", c.open());
    }

    //@Test
    public static void test5() {
        QuangComboLock c = new QuangComboLock(15, 28, 4);
        c.turnRight(15);
        c.turnLeft(28);
        c.turnRight(4);
        //assertTrue("Should open and did", c.open());
    }
} 
...