Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Art and Science of Java Chapter 4 Exercise 7 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Art and Science of Java Chapter 4 Exercise 7" Watch "Art and Science of Java Chapter 4 Exercise 7" New topic
Author

Art and Science of Java Chapter 4 Exercise 7

Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
Hi all,

NOOB in the house - Here is my first question and most probably the first of very many!

After trawling through various threads I am still at a loss as most threads I have read refer to arrays and arrays haven't been covered by the book yet.

Rather than someone providing me a solution can someone provide a hint at how to tackle the following exercise:

____________________________________________________________________________________________________


Rewrite the DigitSum program given in Figure 4-6 so that instead of adding the digits in the number, it generates the number that has the same digits in the reverse order, as illustrated by this sample run:

Here is the code I am supposed to modify



I believe I understand what the code above is doing however I have no idea of how to apply some reverse logic on it.

Many Thanks!

MeatyChi
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Welcome to the Ranch

Did you know the transverse sum of the digits of an integer number allows you to calculate the remainder when dividing by 9? What you always wanted to know!

You can read about arrays here. What it doesn’t tell you is that you can traverse an array with a for loop. Another thing you don’t see is that you can get the individual chars from a String with this method. Beware: the char '0' does not evaluate to 0, but you can subtract '0' from it, and get a number.

Now you can enter the String "123456789" and write down on a piece of paper how you are going to divide that into an array, then how you are going to go through it and add up the individual digits. Do it all on paper first. Don’t even think of writing code until you get the logic worked out.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
If you follow my suggestions you will need to read String s from the input rather than int n.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

As with most problems, in or out of Computer Science, one important early step is to break it down into smaller pieces that can be solved and tested independently of each other.

So, if you're supposed to reverse the digits of a number, it seems that two of the steps might be:

1) Break the number down into individual digits.

2) Reverse the order of some individual digits.

Note that these two are totally independent of each other. You can break a number down into digits without regard to what you'll do with those digits afterwards. The same procedure that breaks the number up can be followed by summing (as apparently done in the previous problem) or reversing (as we want to do here), or multiplying or whatever. Likewise, once you have a bunch of individual digits, you can reverse their order, regardless of where they came from.

You don't even have to think about step 2 when solving step 1, and vice versa.

A reasonable first cut would be that each step will be its own method. Note that it's not always this way, and we might combine a couple steps, or split one step into smaller, more detailed steps, which in turn map to smaller methods. But it's a good initial swipe to figure that one step is approximately one method.

And note that the above has been done totally without regard to Java. We can even go further, without thinking about Java at all. For instance, in step 2, we start with the presumption that we have a list of digits, and we can describe how to access a particular element in that list. We can then describe, in English or pseudocode or Esperanto or whatever, the very simple, straightforward, basic, precise steps that go into reversing the order of that list of digits.

Now, and only now, once we understand the steps without regard to Java, can we start to translate them to Java. For instance, in this case we might decide that our list of digits will be an array that our Step 2 method receives as a parameter.

At this point, you should be able to start writing the Step 2 method, or, if you're not familiar with arrays, google for java array tutorial and study up.

For Step 1, the splitting of a method into digits, the code you pasted in already has a good start on that. Study that code, and make sure you understand how each digits shows up there, and then try to figure out how to use that to write the Step 1 method.

For each step, once you think you have the code written, write a tiny program whose main() method just executes that step with known, hardcoded inputs for which you know what the result should be. If it works, great, move on to the next one, and when they both work, combine them. But if something doesn't work, since you're only testing one small piece, you have a manageable amount of code to debug.
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
Hi Campbell & Jeff,

Thanks for your suggestive reading. The book doesn't delve into Arrays until chapter 10 so it looks like its a For Loop solution at this stage.

I will however come back to this problem and use arrays once I get to the grans realms of Chapter 10.

I'll have to work my way through the Oracle tutorials once I get this book finished.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Meaty Chi wrote:
Thanks for your suggestive reading. The book doesn't delve into Arrays until chapter 10 so it looks like its a For Loop solution at this stage.


For loops and arrays are not mutually exclusive. In fact, they go together all the time. You rarely see an array without a for loop somewhere nearby, and you rarely see a for loop without an array, unless it's iterating over a Collection, which is a lot like an array.

Also, if you don't use an array (or a List), you basically have two approaches: 1) Have as many distinct variables as the maximum possible number of digits in the number, which is easy, but tedious, and leads to ugly code that doesn't scale well, or 2) Use recursion, which for beginners is usually a lot harder to get one's head around than arrays.
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
In that case I'll jump straight in with the arrays!
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
I don't suppose either of you have read this book?

Would it be better if I skipped over to the Oracle tutorials?
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Meaty Chi wrote:I don't suppose either of you have read this book?


Not I. I didn't see where you mentioned which book it is though either, so I don't know if others will know whether they've read it.

[EDIT: Nevermind. I see it. And no, I still haven't read it. (Note to self: Always check the thread topic, dummy.)]

Would it be better if I skipped over to the Oracle tutorials?


Unless the book is an overall horrible one like Schildt, there isn't really a "better" or "worse." Two or more different resources can complement each other. Ultimately it's up to you to see which best fits your learning style, and how to use them both to your own greatest advantage.

I certainly would advise keeping the Oracle tutorials up in a browser, and cross-referencing them when anything in the book is dubious or confusing. After all, they're free and, barring network or server problems, available whenever you're at your computer.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Actually, if you simply want to reverse the digits and print them, that is quite simple. Get your pencil out again, and write. You may find this very useful, but it may take you an hour or so to work out how to use it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
. . . and you are probably best off continuing with the book.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Campbell Ritchie wrote:Actually, if you simply want to reverse the digits and print them, that is quite simple


Yeah, I take back part of what I said. It can be done without arrays or recursion.
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
I worked it out in pencil and have had a very rough bash at putting it into code.

This will scare you so be prepared:



so as you can see I have all the components however it is limited to a four digit integer and I don't know the syntax to print out the variables num1,num2.... in a horizontal axis.

please excuse the println strung everywhere I just left them in to show some checks.

can you tell me the syntax to display the four num(s) on a single line?
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
Here is a link to the book - it seems to be quite popular and it is used as part of the CS106a programming Methodology course at Stamford Uni.

The Art and Science of Java

Thanks again for the link reference strings, however again this topic hasn't yet been covered by the book (chapter 8) so I can only assume there is a really basic way of doing this.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Meaty Chi wrote:it is limited to a four digit integer


You can use a loop like the original code did, and just keep dividing the number until you get zero. Note that you don't need a, b, c, d, num1, num2, num3, and num4 all at the same time. You only need a couple at a time, no matter how many digits you have.

and I don't know the syntax to print out the variables num1,num2.... in a horizontal axis.


Calling print(x) instead of println(x) will print x without a newline.

please excuse the println strung everywhere I just left them in to show some checks.


No problem. That's a great way to debug and to make sure that your code is doing what you expect each step of the way.
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
Finally I have it, well almost:



I am still having problems appending the text "The number reversed is " without it printing it out four times.

I have tried

and

neither produce:

"The number reversed is 9271"

Grrrrrr!
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Meaty Chi wrote:
neither produce:

"The number reversed is 9271"


What do they produce?
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
Sorry I could have phrased that better.

the code produces the 9271 but I cannot append the text to it.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
You can try recursion, but it is far better to use a loop. That bit with 4 print statements is inelegant. what you want is like adding, but you do something different with the numbers. Did you read the links I posted earlier?
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
Is "Meaty Chi" your real name?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Dennis Deems wrote:Is "Meaty Chi" your real name?
Thank you for noticing.

It probably is, yes.
M Ford
Greenhorn

Joined: Mar 06, 2012
Posts: 10
Meaty Chi wrote:Finally I have it, well almost:



I am still having problems appending the text "The number reversed is " without it printing it out four times.

I have tried

and

neither produce:

"The number reversed is 9271"

Grrrrrr!



Well thank you for your solutions as I just could not figure it out without assessing your solution but to answer your question, I've managed to modify your solutions slightly and as you can see, the finish product did indeed show 9271

/*
*File: ReverseDigits.java
*
*/


import acm.program.*;

public class ReverseDigits extends ConsoleProgram{
public void run(){
println("This program generates the number that has the same digits in the reverse order.");
int n = readInt("Enter a positive integer: ");
int a = n % 10;
int b = n % 100;
int c = n % 1000;
int d = n % 10000;
int num1 = a;
int num2 = (b-a)/10;
int num3 = (c-b)/100;
int num4 = (d-c)/1000;

println("The same digits in the reverse order is " + num1 + num2 + num3 + num4);

}


}
Meaty Chi
Greenhorn

Joined: Feb 16, 2012
Posts: 9
Hi M Ford - I'm glad I could help however if you want to follow the book using the code it provided then you need to look at the solution below.

After all the bamboozling around how to print the text it was simply a case of moving the text "The reversed number is " outside the loop

Chris Sill
Greenhorn

Joined: Apr 11, 2012
Posts: 2
Hi all,
I'm new on here and working my way through the Art and Science of Java book. This site has been really helpful already. I have two questions about the ReversedOrderDigits program.

1.) Why does the program only work with the line "int nextNum = 0;" initialized inside the loop?

2.) Could someone explain the difference between "print" and "println"? How do the reversed digits appear at the end of the text using "print"?

Thanks in advance,

Chris S
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Welcome to the Ranch

What do you mean about “only works”? You should tell the details of what goes wrong. You can find about println and print from those links to their API documentation. If you can’t see the difference, please ask again.

In future, please ask new questions in threads of their own.
Chris Sill
Greenhorn

Joined: Apr 11, 2012
Posts: 2
Sorry, but I'm very new at this. I was referring to the post that this thread is referring, "Art and Science of Java Chapter 4 Exercise 7." If I take the line "int nextNum = 0;" out of the while loop and place it outside of the loop (above the loop) and enter 1729 into the program; it returns the number 9161819. If i put it back inside the loop, it returns the correct sequence of numbers, 9271. I was under the impression that the initialization should be done outside of the loop, clearly I was wrong about that, but now I'm confused and was hoping that someone might be able to enlighten me. As for my question about "print" and "println," I'm happy to look them up but I have no idea what API documentation is. Sorry to be so naive.

Chris S
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
You will find out what API documentation is from the links. Whoever is teaching you ought to have told you about it already. It might be difficult to understand, but that is something different! I suspect the print and println methods used in that Art and Science example are specially-written methods from the package supplied with the book. I bet they work very similarly to the methods in those links, however. They may be quoted incorrectly in the example.

I don’t know how you are getting 9161819. I thought you meant why doesn’t it compile if you miss out the = 0; bit. It is rather inefficient writing a local variable which you repeatedly zero; you could simply write . . . but the difference in execution time will be a few μs only, or even less.
If you don’t zero nextNum, you get it set to 9 first time, then you add 172 % 10 (2) and get 11, then you add 17 % 10 and get 18, then you add 1, but I cannot see how you get 9161819. Are you repeating the loop several times?
joseph hall
Greenhorn

Joined: May 28, 2012
Posts: 1
I find by adding the 'print("The number reversed is " )' before the loop nextNum appends as needed. Hope this help.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Welcome to the Ranch, Joseph Hall
E t Wolvov
Greenhorn

Joined: Aug 29, 2012
Posts: 1
Hi, just joined the Ranch.
Im also reading that book, and working now on chapter 4 exercises, here is the code i came up with:


As you can see, i simply multiply the reversed digits by 10 each time i add a digit.
c mcgregor
Greenhorn

Joined: May 17, 2013
Posts: 2
Hi, I'm new to the ranch and like many people here, am doing the Stanford course and reading "The Art & Science..". I was completely baffled by this problem, but after looking at Meaty Chi's solution:




Why does that work? What I mean is why does print ("The reverse of the digits is "); get printed out if the program is running in a logical top to bottom order? I understand the rest of the code quite well, however. (My initial problem with this was that I was using int nReversed outside the while loop so it wasn't resetting at 0 each time.) This site has been fantastic!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Welcome to the Ranch
Always use the code button; I have been back to yor code and you can see how much better it looks
Why are you resetting the value to 0 and adding to it every iteration? You know you don't even need a local variable if you simply print out the last digit, as you will find in one of my posts from last year.
There is nothing backwards about the logic. All you are doing is taking the last digit first. The instruction to print is presumably calling an inherited method, which I suspect looks like this, but I am not certain:-I am not sure how you call the run() method in your ConsoleProgram applications.
c mcgregor
Greenhorn

Joined: May 17, 2013
Posts: 2
Thanks Campbell Ritchie, for the help and the advice.

I went back and took another look at your post from last year as well. In the free Stanford stuff and the Art & Science book, we just haven't covered a lot of things yet, but I think I'm going to also start reading through those oracle tutorials you posted about print and println to give myself some information that this class/book isn't readily telling us.

Thanks for welcoming me again!

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
You're welcome
shayne peterson
Greenhorn

Joined: Dec 30, 2013
Posts: 1
Hi all,

I am also doing the Stanford course and the book at the same time. I find the book is quite a bit ahead of the course but it is still good fun.

I completed this problem earlier today. The way I went round it was to % 10 the entered number, then take that remaindered number and add it to another variable i called numberReversed. I then multiplied numberReversed by 10.
eg
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
Welcome to the Ranch
I have added code tags which you should always use, to your pseudocode, and tried moving the spaces to make it look better.
Let's see if you can't do it without the division by 10 at the end.
Dennis Ouyang
Greenhorn

Joined: Mar 18, 2014
Posts: 3
Hi all. I am also taking the Stanford CS 106 course, and here is my solution to chapter 4 exercise 7. The only issue I see is that it doesn't produce good looking output if you enter a negative integer for n, for example, -12345 will produce -5-4-3-2-1.

Chris R Barrett
Ranch Hand

Joined: Dec 05, 2013
Posts: 88
    
    5

Hi Dennis,

You should review the post right above yours about using code tags so Sheriff Ritchie doesn't have to repeat himself for a third time in this thread.

Cheers!
Chris
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38441
    
  23
If he's new, then I don't mind adding code tags. I have also got rid of the excess blank lines, and broken the long line, so you can see how it is done.
And welcome to the Ranch

Why have you get a serial version ID?
It does say specifically that you should enter a positive number. You can try using the ?: operator to change the digits to positive, but I shall keep quiet about how it is done.
Robert D. Smith
Ranch Hand

Joined: Oct 04, 2013
Posts: 143
    
    5
There are a couple of ways to fix the negative number issue. One could always multiply the negative number by -1. There is a method in java.lang.Math that will do what you need. And since I'm an a** and don't like users that can't follow directions, I would look for something in Winston's article, User Input and make the user enter numbers until they get it right. Not really, but it is an option.

Hope I didn't give away too much, but as a rather new Java developer, a hint on where to find methods helped a great deal when I was first starting.

Regards,
Robert


There are worse crimes than burning books. One of them is not reading them. Ray Bradbury
 
 
subject: Art and Science of Java Chapter 4 Exercise 7