• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Writing a loop statement to stop at 3 and inserting a break to quit loop

 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey everybody, I am posting this because I am having trouble with the last few steps of my program. I am currently trying to write a loop that ends at 3 times (the user only has 3 times to enter and get the answer correct and if they don't it breaks loop). Also I am having trouble assigning the values once the user has moved one stack to another.

Here is my code:


import java.util.Scanner;

public class ToothpickPuzzle {

static int A,B,C; // did this so I can access ABC to all the functions.
//static means its allocated the entire time the program is run and can access the data
public static void main(String[] args)
{

// create an instance of this class
ToothpickPuzzle theSampleInstance = new ToothpickPuzzle();
// call a non-static method to do everything else
theSampleInstance.mainLoop();
}//CLOSED

void mainLoop()
{//OPEN
Scanner keyboard = new Scanner(System.in); // creating and object of the class scanner, name=keyboard! good name.

//identifying information.




//Game instructions
System.out.println("Welcome to the Toothpick Puzzle.Think of having 3 piles of toothpicks in front of you, where there are 24 toothpicks total:"); // intro
System.out.println(" Stack: A B C");
System.out.println("Number of Toothpicks: 11 7 6 ");
System.out.println("The goal is to create 3 piles of 8 toothpicks in exactly 3 moves.");
System.out.println("A move consists of moving toothpicks from one stack to a second stack, where the number of toothpicks moved is exactly the number that is in the destination stack.");
System.out.println("In other words, to move from stack B (7 toothpicks) to stack C (6) as shown above, we would move 6 from B to C, leaving us with 1 in B and 12 in stack C.");
System.out.println("Here we go...");

System.out.println(" Stack: A B C");
System.out.println("Number of Toothpicks: 11 7 6 ");

String userInput = "";
String userInput2= "";


A = 11;
B = 7; // A+B+C=WIN! (casting abc to integers)
C = 6;
char stackFrom, stackTo; //string names which will be converted to char
int stackFrom_size, stackTo_size; // sizing them up
stackFrom_size = 0;
stackTo_size = 0;
stackFrom = ' '; //NULL CHARACTER
stackTo = ' ';

while(true) //truth loop
{




//prompts user for beginning stack
System.out.print("1. Enter stack from: ");
userInput = keyboard.nextLine(); // read user input n stuff
stackFrom = userInput.charAt(0); // converts string to char and grabs the first letter in the string. An array sort of.
stackFrom_size = GetNumberOfToothpicks(stackFrom);// calling function to take stack from

//prompt user to enter ending stack.
System.out.print("Enter stack to: ");
userInput = keyboard.nextLine(); //collecting information n such
stackTo = userInput.charAt( 0); //converts string to char and grabs the first letter in the string.
stackTo_size = GetNumberOfToothpicks(stackTo);//calling function to stack to

}



System.out.println(" Stack: A B C");
System.out.println("Number of Toothpicks: " );
//System.out.println("StackFrom: " + stackFrom_size + " + StackTo: " + stackTo_size);


if(stackFrom_size < stackTo_size)
{
System.out.println("Sorry not enough toothpicks in " + stackFrom + " try again.");
continue;
}//closing if statement

else //continues the move if valid
{
DoMove(stackFrom,stackTo); //calls method from DoMove
}// close else



}//while(true) loop closing
}//mainLoop Closing.

// +----+-----+RETURNS TOOTHPICKS IN A GIVEN FILE+----+-----+

public static int GetNumberOfToothpicks(char pile)
{
int numberThatIWant;
numberThatIWant = 0;
switch(pile)
{
case 'A':
numberThatIWant = A;
break;
case 'B':
numberThatIWant = B;
break;
case 'C':
numberThatIWant = C;
break;
default:
break;

}//closes switch
return numberThatIWant; // returns the number in the pile
}//closes function 1

public static void DoMove(char stackFrom,char stackTo)//move it
{
// get stack sizes

int stackFrom_size = GetNumberOfToothpicks(stackFrom);
int stackTo_size = GetNumberOfToothpicks(stackTo);

//calculate new stack sizes

stackFrom_size = stackFrom_size - stackTo_size; //subtract what was taken
stackTo_size = stackTo_size * 2; // the stack the toothpicks are put in, doubles.

SetNumberOfToothpicks(stackFrom, stackFrom_size);
SetNumberOfToothpicks(stackTo, stackTo_size);


}//closes function 2

public static void SetNumberOfToothpicks(char stack, int stack_size)
{
switch(stack)
{
case 'A':

A = stack_size;
break;
case 'B':
B = stack_size;
break;
case 'C':
C = stack_size;
break;
default:
break;

}
}

}//closes entire program



The program works, but as said before I am having trouble showing the NEW stacked values. So if I move B to C, it does the math, but I need the new println to show the new stack values, so it would be: A,B,C = 11 1 12. Can anyone help?

 
Ranch Hand
Posts: 210
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
one thing i would suggest is to paste that into a so everyone can read it easier.
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
at line 68 is where I would like to start this loop statement that loops 3 times. It is supposed to end as either, the person finishes the code and the user stacks them in 8's within 3 tries or the program ends.

Also at line 86 is where I want to print out what the new stack numbers are, so if I move stack B to C, it then shows A B C = 11 1 12

Can anyone help me?

Thank you!
 
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
- What are those OPEN and CLOSE things for?
- Skip saying things like "// closes function 2"; it doesn't help. Plus it's wrong, because the order in the file is (a) irrelevant, and (b) subject to change.

Keep a counter, every time the user enters a valid value, reset it to zero, every time they enter an invalid one, increment the counter, and if it's greater than the number you want to allow, either break out of the loop, or throw an exception, or...

I'm not sure I really agree with your definition of "static", either, nor would I include an explanation of the Java language in the code itself.

I'd also move things like the game instructions into a method named something useful, like "displayGameInstructions", eliminating the need for your two redundant comments.
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for your very critical response. I was expecting maybe a little help on what I posted for not really on my comments. I know my comments are either A)not truthful or B) irrelevant to others. However my comments are for reminders for myself on what I am doing and they are useful to me. I am not an expert or even moderate in this programming language and was looking for some guidance, not to be slammed. Thanks anyway folks, I'll bring my comments elsewhere.
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And you got it, but choose to ignore it.

David Newton wrote:Keep a counter, every time the user enters a valid value, reset it to zero, every time they enter an invalid one, increment the counter, and if it's greater than the number you want to allow, either break out of the loop, or throw an exception, or...

If you post code, you're going to get a wide variety of responses. That is the nature of the internet.

If you expect people to help, you must post code that is as concise and clean as possible: misleading or extraneous comments detract from the readability of the code in question. The easier the code is to read and comprehend the more likely you are to get help: the idea is to make it as easy as possible for people to help you.
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There are a couple of things that I notice about your code:

Big methods. Big methods are usually hard to comprehend and should be refactored to smaller methods.
You're not really using an object oriented approach. If you have toothpick stacks with a number of toothpickes and an associated character why not make a class of it? Same goes for the game itself.
Some comments do more harm then good: "}//CLOSED" What does that add to clarify the code?
You don't always use proper indentation which makes it a lot harder to read.
Your main method contains application code while it should only be used to start your program.

I believe that if you fix these problems that your insight of how your code works will increase and thus making it easier to solve problems.

About your question, why not implement something like:


// Damm I'm late
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
well I find it easy, unfortunately others don't. i am learning the language so I am commenting everything to help me. I understand the counter what you posted. The thing is the counter will count to three if the user gets it right. So if the user takes a stack from B to C, that is a valid move since B has more toothpicks than C, which is 1 move.

However, C can't be moved to B which is why I made the truth loop as well as the if and else statement and it re-loops (doesn't count as a move). I am having trouble putting the loop statement in the right context within the program, so if the user makes 3 moves and is unable to make (8,8,8) the loop ends and says "sorry try again".

If the user however, makes it in three tries, it says "congrats".

I wanted to do

int = loopCounter = 0;

while (loopCounter <=3)
{

loopCounter = loopCounter +1;

}

for each loop, I am just unsure if this is the correct form?
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Wouter, I understand that completely, however where would I put that? Underneath the truth loop? (The truth loop must continue till end).
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That'd be one way of doing it, although I feel Wouter's suggestion reads a bit more like the problem statement. Ultimately it's the same thing, though; I think you could do it either way.
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, that would replace the forever loop.
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(I also mis-read the original post; I thought the three-thing was for invalid guesses.)
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My bad. Should have been:

And about the invalid moves. Code something like:
Which can be combined with the code I posted earlier.

You could create a new Game object after each game. Something like:
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
heh, well, this thing is complicated, im pretty bad at JAVA
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's a good thing. Then the worst that could happen is that you learn something. We all had to learn it. I know I'm still learning every day.
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks for your help Wouter, I'll try to edit my code as such. Funny thing is, this is only part 1 of 3. I will see what happens.. I don't know if I should re-write my code? I've been struggling all weekend with just this and it's due Tuesday. :|
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your welcome. I would not rewrite the code but try to improve it. Good luck!
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I wouldn't start re-writing it yet, but you might want to once you have something closer to working.

Wouter's suggestion of creating more, smaller methods is a good one: small code is easy to reason about. The fewer side-effects code has the easier it is to reason about. The more the mainline code reads like the problem you're trying to solve the easier it is to reason about. For example, Wouter's main loop is essentially what I ended up refactoring your code to: it reads like the problem. Mine looks like this, only slightly pseudo-coded:Your code is more or less correct, by the way--you are not very far off at all, which is why Wouter and I are providing as much pseudocode as we are; you are clearly showing effort and doing your own homework.
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
update

now it loops only 3 times, and I am in the process of writing the statements of either: congrats you got 8,8,8 in 3 tries, or sorry try again. Thanks for help everyone. But this is only part 1 of 3, the next part is having the computer solve it by itself.. :///

 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Congratulations--see, you weren't far off! (Although now the comment "truth loop" is... questionable.)

I'm assuming the code isn't actually indented like that and something horrible happened during the cut-and-paste process?

Before proceeding to the next stage, I'd *strongly* recommend that you spend some time refactoring, making the code look more like Wouter's or mine--it'll make the next step that much easier. I'd also suggest not having the stack counts be static, and ditching the static methods as well.

 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I will try to fix it up as best as I can, I am learning a lot (I have spent all weekend on this), the truth loop was a mistake because of something I had before in there which I removed.

The cutting and pasting started from here actually. When I copied and pasted my code earlier on here, I made a mistake somewhere which screwed up my entire program, so i erased (wasn't saved) and had to copy from here to eclipse which ended up making my code like this..

Any suggestions on how to start the 2nd process? with the computer solving the problem? I know it won't be an interactive interface due to it being the computer. I am just unsure of what will change in code? I just know that the computer will have to get to the code (8,8,8).
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I also just realized my continue statements under my IF, ELSE commands continue whether or not the move was valid or not. uh oh. I wanted it where it re-loops and gives the user another try (not docking them 1 move for the mistake).
 
David Newton
Author
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Cal Mil wrote:[...] copy from here to eclipse which ended up making my code like this.


Eclipse can format your code for you--it makes reading it substantially easier.

Any suggestions on how to start the 2nd process?


Not yet, although once you do get started, I'd recommend starting a new thread with any specific questions, as this one has gotten a little long.

There are a number of ways to start thinking about having the computer solve this problem, from simplistic brute force to various AI techniques. Without knowing what the goal or level of your class I'd say just get started and we can take it from there. If nothing else, it's relatively easy to at least figure out which moves are actually legal, and no matter what, you'd need to be able to take those moves into consideration.
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ok thank you and yes i will start a new thread if need be and its CS 102. I have taken 101, but the teacher was too easy and so it's like learning both at once anyway! That's why this has been so miserable for me lol. Thank you (you can lock thread if you want).
 
Cal Mil
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also, sorry Newton and Wouter if I was rude in this post. I was getting furious at this java code (throwing my book around the room, yelling at my computer, etc). I get like that. I just wanted it to end but after suffering through 30+ hours this weekend of Java, I have learned a lot. Thank you both for your help and suggestions.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic