I'm really new to Java and I'm having issues with a program required for my Java class. I need to simulate a lock and implement methods that change combination, check the number on top etc.
Well, I think there's an issue with my openLock() method or alterLockCombination() method. My program will correctly open the lock with default combination (0,0,0) but when I try and change the combination it won't work properly and only the default combination will unlock the lock.
Where are my errors here?
import java.util.Scanner;
public class Lock {
public static final int CLOCKWISE = 0;
public static final int COUNTER_CLOCKWISE = 1;
Scanner in = new Scanner(System.in);
private int x;
private int y;
private int z;
private boolean isLockOpen;
private int noOnTopOfKnob;
public Lock() {
x = 0;
y = 0;
z = 0;
this.isLockOpen = false;
this.noOnTopOfKnob = 0;
}
public void alterLockCombinaiton(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public void turnKnob(int direction, int noToStop){
int i = noOnTopOfKnob;
int numbersPassed = 0;
System.out.println("Simulating......");
do{
if(direction == CLOCKWISE)
i++;
else if(direction == COUNTER_CLOCKWISE)
i--;
if(i > 39)
i = 0;
if (i < 0)
i=39;
this.noOnTopOfKnob = i;
System.out.print(noOnTopOfKnob + " ");
numbersPassed++;
if(numbersPassed>40 && noOnTopOfKnob==noToStop)
break;
}
while(true);
System.out.println();
}
public void closeLock() {
System.out.println("Locked!");
this.isLockOpen = false;
}
public boolean openLock() {
// initializing with arbitrary values
int firstStop = -1;
int secondStop = -1;
int thirdStop = -1;
int firstRotation = -1;
int secondRotation = -1;
int thirdRotation = -1;
for(int i = 1; i <= 3; i++){
System.out.print("Enter a number (0-39) " + i + ": ");
int noToStop = in.nextInt();
System.out.print("Enter 0 for clockwise and 1 for counter-clockwise) " + i + ": ");
int direction = in.nextInt();
turnKnob(direction, noToStop);
if(i == 1) {
firstStop = noToStop;
firstRotation = direction;
}
else if(i == 2) {
secondStop = noToStop;
secondRotation = direction;
}
else if(i == 3) {
thirdStop = noToStop;
thirdRotation = direction;
}
if(firstStop == this.x && firstRotation == CLOCKWISE
&& secondStop == this.y && secondRotation == COUNTER_CLOCKWISE
&& thirdStop == this.z && thirdRotation == CLOCKWISE) {
this.isLockOpen = true;
}
}
return isLockOpen;
}
public boolean isLockOpen() {
return this.isLockOpen;
}
public int getNoAtTop() {
return noOnTopOfKnob;
}
}
END of Lock.java
import java.util.Scanner;
public class LockInput {
public static void main(String[] args) {
System.out.println("\nWelcome to lock simulator");
System.out.println("-------------------------------------------------");
menu();
}
public static void menu() {
Scanner scnr = new Scanner(System.in);
Lock newLock = new Lock();
int xInput, yInput, zInput;
System.out.println("\nSelect an option for the lock.\n");
System.out.println(" A : Set a new lock combination. ");
System.out.println(" B : Close the lock.");
System.out.println(" C : Attempt to open the lock.");
System.out.println(" D : Check lock status.");
System.out.println(" E : Check current top number.");
System.out.println(" Q : Quit program.");
char menuOption = scnr.next().charAt(0);
menuOption = Character.toUpperCase(menuOption);
switch(menuOption) {
case 'A':
System.out.println("Set a new combination for the lock.\n");
System.out.println("Enter the first number of the combination.");
xInput = scnr.nextInt();
System.out.println("Enter the second number of the combination.");
yInput = scnr.nextInt();
System.out.println("Enter the third number of the combination.");
zInput = scnr.nextInt();
newLock.alterLockCombinaiton(xInput,yInput,zInput);
menu();
break;
case 'B':
newLock.closeLock();
menu();
break;
case 'C':
newLock.openLock();
System.out.println("-------------------------------------------------");
System.out.println("After lock open attemp....");
System.out.println("No on top: " + newLock.getNoAtTop());
System.out.println("Lock is open: " + newLock.isLockOpen());
menu();
break;
case 'D':
System.out.println("Lock is open: " + newLock.isLockOpen());
menu();
break;
}
}
}
LockInput class is unfinished since I'm trying to figure out my input issue first.
The problem is that you are creating a new Lock() each time menu() is called.
So, the modified combination will be immediately replaced by the default one since menu() gets called just after that, and the lock replaced by a new Lock instance :
newLock.alterLockCombinaiton(xInput,yInput,zInput);
menu();
You may want to remove Lock newLock = new Lock(); from menu(), and declare it as a static variable at the class level instead :
static Lock newLock = new Lock();
Better yet, as suggested by #GhostCat to avoid the static variable :
Create the object in the main method
Lock newLock = new Lock();
Change the menu() method to menu(Lock newLock)
Then call it from main : menu(newLock);
The same goes for the Scanner variable, you'll probably figure that part out .
Related
I have two classes: MyNumbers and MyScanner. I am trying to pass the validated inputs to the calculateSum (int x, int y) method in order to print the final result in the MyScanner class, but I don't know how I can take the user inputs from the MyScanner class to pass them to the validate() method in the MyNumbers class so that it allows the calculateSum() method to perform its task.
P.S. validate() method should be void and parameterless, but calculateSum() method should be string to return the result as a string and take two parameters. I also want the validate() method to prompt for user input and validate the values to make sure that they are in the certain range. This method needs to keep prompting until user inserts a valid number.
How can I achieve this without introducing another variable/implementing setters/ passing variables as a parameter to the validate() method?
public class MyNumbers {
int number1;
int number2;
public void validate() {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
validate();
return "Sum: " + number1 + number2;
}
}
public class MyScanner {
public static void main(String[] args) {
MyNumbers myNumbers = new myNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
do{
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.calculateSum(x, y);
break;
}
}
while(option!=0);
}
}
EDIT :
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate() {
int valid=0;
int x;
int y;
Scanner s = new Scanner(System.in);
System.out.println("Welcome!");
do{
System.out.println("Enter Number 1: ");
x = s.nextInt();
if (x >= 10 && x <= 50) {
valid=2;
}
else {
System.out.println("Number 1 should be between 10 and 50");
}
}while(valid!=2);
do {
System.out.println("Enter Number 2: ");
y = s.nextInt();
if(y >= 5 && y <= 20){
System.out.println(calculateSum(x, y));
valid=3;
}
else {
System.out.println("Number 2 should be between 5 and 20");
}
}while(valid!=3);
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + (number1 + number2);
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
myNumbers.validate();
}
}
Try
import java.util.*;
class MyNumbers {
int number1;
int number2;
public void validate(int number1 , int number2) {
if (number1 >= 10 && number1 <= 50) {
if(number2 >= 5 && number2 <= 20){
System.out.println(calculateSum(number1, number2));
}
}
else {
System.out.println("Number should be between 10 and 50");
}
}
public String calculateSum(int x, int y) {
this.number1 = x;
this.number2 = y;
return "Sum: " + number1 + number2;
}
}
public class Main {
public static void main(String[] args) {
MyNumbers myNumbers = new MyNumbers();
Scanner scanner = new Scanner(System.in);
int option = scanner.nextInt();
switch(option){
case 1:
System.out.println("Enter number 1");
int x = scanner.nextInt();
System.out.println("Enter number 2");
int y = scanner.nextInt();
myNumbers.validate(x, y);
myNumbers.calculateSum(x, y);
break;
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I haven't asked many questions on here so sorry if I have laid this question out wrongly.
I am trying to call the variable AmountOfTickets in the main class. So I can update it with each loop of the while loop. I don't know how to properly call the variable without eclipse showing an error.
This is the class where I have created the variable AmountOfTickets which
I am trying to update
public class TicketHandler {
public int TicketCost;
public static int AmountOfTickets;
public TicketHandler(int TicketCost, int AmountOfTickets){
this.TicketCost = TicketCost;
this.AmountOfTickets = AmountOfTickets;
}
public TicketHandler() {
TicketCost = 200;
AmountOfTickets = 50;
}
public int getTicketCost() {
return TicketCost;
}
public void setTicketCost(int ticketCost) {
TicketCost = ticketCost;
}
public static int getAmountOfTickets() {
return AmountOfTickets;
}
public void setAmountOfTickets(int amountOfTickets) {
AmountOfTickets = amountOfTickets;
}
public void ReduceNoOfTickets(int TicketsSold) {
this.AmountOfTickets = this.AmountOfTickets - TicketsSold;
}
}
This is the main program code where I am trying to call the variable and used it
import java.util.Scanner;
public class ApplicationProgram {
static Scanner inKey = new Scanner(System.in);
public static void main(String[] args) {
TicketHandler Red = new TicketHandler (200,50);
TicketHandler Green = new TicketHandler (200,50);
TicketHandler Blue = new TicketHandler (200,50);
TicketHandler Yellow = new TicketHandler (200,50);
boolean running = true;
//Main menu
while (running) {
printMenu();
int KeyIn = inKey.nextInt();
//menu
switch (KeyIn) {
case 1:{
RedRoute();
break;
}
case 2:{
GreenRoute();
break;
}
case 3:{
BlueRoute();
break;
}
case 4:{
YellowRoute();
break;
}
case 5:{
ShowAvailableTicketsAndPrice();
break;
}
case 6:{
System.out.println("Do you wish to quit: type Y to confirm");
String quitYN = inKey.next ();
//System.out.println(quitYN);
if ((quitYN.matches("Y")) || (quitYN.matches("y"))) {
System.out.println("Goodbye\n\n");
running = false;
System.exit(0);
}
break;
}
default:{
System.out.println("Not a valid option, try again.");
break;
}
}
}
}
public static void printMenu(){
System.out.println("Bus Tickets");
System.out.println("---- ----");
System.out.println("1. \tRedRoute");
System.out.println("2. \tGreenRoute");
System.out.println("3. \tBlueRoute");
System.out.println("4. \tYellowRoute");
System.out.println("5. \tShowAvailableTicketsAndPrice");
System.out.println("6. \tQuit");
}
public static void RedRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200) {
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void GreenRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200){
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void BlueRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int moneyin = 200;
while (moneyin <= 200){
System.out.println("Insert £" + moneyin);
int KeyIn = Red.nextInt();
moneyin = moneyin - KeyIn;
if (moneyin == 0){
System.out.println("Enjoy");
AmountOfTickets = get.AmountOfTickets - 1
break;
}
}
}
public static void YellowRoute(){
Scanner Red = new Scanner(System.in);
System.out.println();
int count = 200;
while (count <= 200) {
System.out.println("Insert £" + count);
int KeyIn = Red.nextInt();
count = count - KeyIn;
if (count == 0){
System.out.println("Enjoy");
break;
}
}
}
public static void ShowAvailableTicketsAndPrice(){
System.out.println("Routes available:");
System.out.println("\tRed route, Tickets left: "+ "Price: ");
System.out.println("\tBlue route, Tickets left: " + "Price: ");
System.out.println("\tGreen route, Tickets left: " + "Price: ");
System.out.println("\tYellow route, Tickets left: " + "Price: ");
}
}
Thank you.
First of all, your var called AmountOfTickets is static, it means one copy will live to all objects, also your method getAmountOfTickets.
you have a problem here
AmountOfTickets = get.AmountOfTickets - 1
you must call the variable using the ClassName.YourVar like this:
TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1;
also your method.
Also you could import a static like this:
import java.util.Scanner;
import static huh.TicketHandler.*;
so you can use:
AmountOfTickets = getAmountOfTickets() - 1;
"You could think in create an object and call the var like this"
public static void BlueRoute(){
Scanner Red = new Scanner(System.in);
TicketHandler objectOne = new TicketHandler(); //HERE I CREATED AN OBJECT
System.out.println();
int moneyin = 200;
while (moneyin <= 200)
{
System.out.println("Insert £" + moneyin);
int KeyIn = Red.nextInt();
moneyin = moneyin - KeyIn;
if (moneyin == 0){
System.out.println("Enjoy");
objectOne.AmountOfTickets = objectOne.getAmountOfTickets() - 1; //HERE I USED IT
break;
}
But as this is static it will replace objectOne to
TicketHandler.AmountOfTickets = TicketHandler.getAmountOfTickets() - 1; //HERE I USED IT
So, in my humble opinion you can or use an import static (so you avoid to write the same class name before your static), or put the name of your class first then the name and method.
Using an import static could be bad if there is another class with the same name or method as yours and you imported, because compiler could say, hey which one am I suppose to use?
So, I'd rather use fullnameClass.varOrMethod
hope it helps
btw using this: TicketHandler.AmountOfTickets and this: TicketHandler.getAmountOfTickets() are avable to be used in all ApplicationProgra's class code as i said because it is static, and because you difined them public
public static int AmountOfTickets;
public static int getAmountOfTickets() {
return AmountOfTickets;
}
=) i guess that was what you asked for. c-ya
Part of my java code is not running. I am fairly new to java and have been working out some new environment changes. My class was told to build a windchill temperature calculator. My main issue is that my code works up to the for (ws = wsp; ws <= c; ws += 0.5) then stops.
import java.util.*;
class Assign1
{
public static void main(String args[])
{
Menu user = new Menu();
Menu.mainmenu();
user.acceptSelection();
}
}
class Menu
{
public static void mainmenu()
{
System.out.println("Temperature Analysis MENU");
System.out.println("1.W)ind Chill Temperature");
System.out.println("0.E)xit");
System.out.println("Enter Selection:");
}
public void acceptSelection()
{
Scanner stdin = new Scanner(System.in);
String selection = stdin.nextLine();
char choice = selection.charAt(0);
switch(choice)
{
case 'W':
case 'w':
case '1':
processing.process(); break;
case 'E':
case 'e':
case '0':
System.out.println("E"); break;
}
}
}
class processing
{
public static void process()
{
Scanner stdin = new Scanner(System.in);
System.out.println("\n\n\n\n\n\n\n");
System.out.print("Please enter START air temp in celsius (decimal) MUST be BELOW 9: ");
double sa = stdin.nextDouble();
System.out.print("Please enter END air temp in celsius (decimal) MUST be BELOW 9: ");
double ea = stdin.nextDouble();
System.out.print("Please enter wind speed (decimal) FROM 8km/h to: ");
double w = stdin.nextDouble();
System.out.println("\n==================================================================\n");
calculation(sa, ea, w);
}
public static void calculation(double a, double b, double c)
{
double wsp = 8.0;
double airTemp;
double ws;
int size = 150;
double[] wChill = new double[size];
int count = 0;
System.out.print(" " + a);
while(a <= b)
{
System.out.print(" " + a);
a +=5;
count++;
}
System.out.print(" " + b);
int count2 = 0;
while(wsp <= c)
{
count2++;
wsp += 0.5;
}
double[][] chart = new double[count2][count];
int i = 0, j = 0, k = 0;
This is where it stops working. I cannot get it to print my loop out. Any help in fixing my problem would be appreciated as well as notes to my code as i am trying to improve. I am using JGrasp if it helps.
for (ws = wsp; ws <= c; ws += 0.5)
{
System.out.println(ws + " ");
for (airTemp = a; airTemp <= b; airTemp += 5.0)
{
if ((ws + 0.5) > c)
{
System.out.printf( "%2d %2d", c , chart[k][i]);
}
else
{
wChill[i] = (13.12 + (0.6215*airTemp)+(-11.37*Math.pow(ws, 0.16))+(0.3965*airTemp*Math.pow(ws, 0.16)));
chart[k][i] = wChill[i];
System.out.print(chart[k][i] + " ");
}
i++;
}
k++;
}
}
}
According to you code you have a while loop
while(wsp <= c) {...}
then you have a for loop
for (ws = wsp; ws <= c; ws += 0.5)
so as you can see ws is assigned the value of wsp which has in the while already exceeded the value of c
Can someone edit my code to make it loop the selection menu. If the choice is not one of the 5 options it will prompt the user to re-enter until it is a valid option. If possible an explanation would be helpful as well. Thanks
Here is my code.
import java.util.*;
public class ShapeLoopValidation
{
public static void main (String [] args)
{
chooseShape();
}
public static void chooseShape()
{
while (true){
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
//while (true) {
if (shapeChoice >= 1 && shapeChoice <=4)
{
if (shapeChoice == 1)
{
circle();
}
else if (shapeChoice == 2)
{
rectangle();
}
else if (shapeChoice == 3)
{
triangle();
}
else if (shapeChoice == 4)
{
return;
}
}
else
{
System.out.print("Error : Choice " + shapeChoice + "Does not exist.");
}
}
class Test {
int a, b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
}
}
First: take a look at switch
Second: read a bit about do-while loops (they are usually a good fit for this kind of situations).
Now, how I would implement it (but you should really learn how to make a loop in this scenarios):
public static void chooseShape () {
boolean valid = false;
do {
Scanner sc = new Scanner(System.in);
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
switch (shapeChoice) {
valid = true;
case 1:
circle();
break;
case 2:
rectangle();
break;
case 3:
triangle();
break;
case 4:
return;
default:
valid = false;
System.out.println("Error : Choice " + shapeChoice + "Does not exist.");
System.out.println("Please select one that exists.")
}
} while (!valid)
}
Use do-while flow control until EXIT code entered:
int shapeChoice;
do {
System.out.println("Select a shape number to calculate area of that shape!");
System.out.print("Circle = 1. \nRectangle = 2. \nTriangle = 3. \nExit = 4. \nINPUT : ");
int shapeChoice = sc.nextInt();
// then use if-else or switch
} while (shapeChoice != 4);
OR
use break statement to loop break at your code as bellow:
else if (shapeChoice == 4)
{
break;
}
I'm trying to get my loop to go over and over again until the user types in "quit" then it will quit.
Basically I'm trying to get my Finch robot to change nose color depending on how it's positioned, but I'm confused on how to get it to allow the user to position it again after it has already been positioned so that the nose color can change color multiple times. When it first runs the Finch will execute the code but quits immediately afterwards.
Here is my code:
public class finch {
public static final int INCREASE = 20;
public static final int SEC = 1000;
public static final int MAXSPEED = 255;
public static final int HALFSEC = 500;
public static Finch myFinch;
public static void main(String[] args) {
myFinch = new Finch();
Menu();
}
public static void Menu() {
Scanner console = new Scanner(System.in);
System.out.println("Enter your choice:" + "");
int input;
int input1;
boolean flag=true;
while(flag){
System.out.println("1.\t" + "Rolling" + "Finch");
System.out.println("2.\t" + "Obedient" + "Finch");
System.out.println("3.\t" + "Exit");
System.out.println();
System.out.println("Enter your choice:");
System.out.println();
input = console.nextInt();
flag=false;
if (input == 1) {
//input = DarkFinch;
System.out.println("Position the Finch \"down\" or \"up\" to change nose color");
rolling(myFinch);
} else if (input == 2) {
// input = ChasetheFinch;
// System.out.println("Chase The Finch");
} else if (input == 3) {
// input = Exit;
System.out.println("Goodbye");
} else {
// System.out.println("Try again");
flag=true;
/* return Menu(); */
}
}
}
public static boolean rolling(Finch myFinch) {//This method will change the Finches nose color depending on the Finches position.
//"up" = place the finch upright standing on its tail
for (int i = 1; i <= 20; i++) {
while (myFinch.isBeakDown() || myFinch.isBeakUp()) {
if (myFinch.isBeakDown()) {
myFinch.setLED(0,0,255,3000);
} else if (myFinch.isBeakUp()) {
myFinch.setLED(255,0,0,3000);
} else {
myFinch.setLED(0,0,0,5000);
}
}
}
return true;
}
}
Don't set your flag = false before the condition on the input value. Set it to false in the if(input == 3) case