Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I have a java program I completed, however, I need it to loop 3 times before it

ID: 3650747 • Letter: I

Question

I have a java program I completed, however, I need it to loop 3 times before it exits.

It's a lock combination program, where the user enters the combo. I want them to be able to enter it 3 times then close.
-------

public class CombinationLock {

String combination;
String check;
CombinationLock()
{
combination="";
check="";
}
CombinationLock(String t)
{
combination=t;
check="";
}
public void setPosition(String a)
{
check=check+a;
}
public void unlock()
{
if(combination.equalsIgnoreCase(check))
{
System.out.println("Unlocked!!");
}
else System.out.println("You're going to jail!!");
}
}

-------------------------------



public class CombinationLockTest
{
public static void main(String [] args)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter the combination [Example: ABC]: ");
String t=s.nextLine();
CombinationLock lock = new CombinationLock ("DEF"); //sets the correct combination of the lockto ABC
lock.setPosition(t.charAt(0)+"");
lock.setPosition(t.charAt(1)+"");
lock.setPosition(t.charAt(2)+"");
lock.unlock();
}
}

Explanation / Answer

public class CombinationLock { String combination; String check; CombinationLock() { combination=""; check=""; } CombinationLock(String t) { combination=t; check=""; } public void setPosition(String a) { check=check+a; } public boolean unlock() { //instead of returning the text, return whether or not the answer is right or not. this will allow us to loop in the driver. return (combination.equalsIgnoreCase(check)); } } -------------------------------------------------- import java.util.Scanner; public class CombinationLockTest { public static void main(String [] args) { CombinationLock lock; for (int count = 1; count 1) { tryOrTries = "tries"; } else { tryOrTries = "try"; } System.out.println("Wrong, try again. " + (3 - count) + " "+tryOrTries+" remaining."); } else //out of tries, going to jail { System.out.println("You're going to jail!!"); } } } }