Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial

Broderic Crowe
1,549 PointsStoring "console.printf" as variable? lol
As you can see in the code below, I'm repeating myself by using console.printf twice, but I don't know how to store it in some variable so I can just call it by rupeeBalance or something. Any help?
do{
String askToBreak = console.readLine("WANNA BREAK A POT? ");
if (yes.contains(askToBreak)) {
rupees -= 100;
console.printf("You have %s rupees remaining\n\n", rupees);
}
if (no.contains(askToBreak)) {
rupees += 150;
console.printf("You have %s rupees remaining\n\n", rupees);
}
}while(rupees > 0);
1 Answer

Steve Hunter
57,710 PointsYou could wrap it up in one function that you pass an integer to? Then just call the method from your loop?
do{
String askToBreak = console.readLine("WANNA BREAK A POT? ");
if (yes.contains(lifeTaker)) {
rupees -= 100;
notSavingMuchCode(rupees);
}
if (no.contains(lifeTaker)) {
rupees += 150;
notSavingMuchCode(rupees);
}
}while(rupees > 0);
private void notSavingMuchCode(int rupees){
console.printf(""You have %s rupees remaining\n\n", rupees);
}
I think there are greater code-crimes out there than breaching DRY using console.printf
, to be honest! There's bigger fish to fry!
Steve.
Broderic Crowe
1,549 PointsBroderic Crowe
1,549 PointsIt does seem like more trouble than its worth for my little example, but I'll keep that in mind. Thanks Steve:)
Steve Hunter
57,710 PointsSteve Hunter
57,710 PointsApologies for the sarcasm; the example wasn't great and I'm in one of those moods. Trying to encapsulate
printf
has been done lots within Java. But seeing where you've got the same line of code, or very nearly the same, is always worth pulling out into a function for reuse - so, yes, you were absolutely right to spot the same code being written twice and flagging that it might be needing a refactor.Good job!
Steve.