Programming Question

SkyHog

Touchdown! Greaser!
Joined
Feb 23, 2005
Messages
18,431
Location
Castle Rock, CO
Display Name

Display name:
Everything Offends Me
I am having a bear of a time with what should be a really simple thing, and was wondering if any programmers could give advice on this.

In Java, I am trying to take a number, lets say 145, and add the individual digits together. I am taking the stupid backwards way in coverting to a string and trying to pull the chars out of it to do it, but I cannot find a way to convert a char to an int. I could convert the char to a string and then to an int, but that is even more backwards. Is there a way to pull a digit from a int like there is a way to pull a char from a string?
 
if it helps, here's my code (remember, I'm new to Java, so no nitpicking my stupidity :D)
Code:
import java.util.Scanner;

/* Written by Nick Brennan for CS152
 * 
 * This program will ask the user to enter a number between 1 and 1000
 * and check to make sure the number is within those bounds.
 * If the number is out of bounds, make the user feel like an idiot and ask for
 * a different number.
 * Then we calculate the sum of the digits in that number
 */

public class Prog_5 {
  public static void main (String[] args){
    Scanner userinput = new Scanner (System.in);
    int inputtednumber;
    int x;
    int addedvalues = 0;
    boolean validnumber = false;
    String intasword;

    do {
      System.out.println ("Please enter an integer between 1 and 1000: ");
      inputtednumber = userinput.nextInt();
      //I'm assuming that by "in a loop" it was inteded to use an if statement within a loop
      if (inputtednumber < 1 || inputtednumber > 1000){
        System.out.println ("Nah, stupid.  I said between 1 and 1000!");
      }  else {
            validnumber = true;
          }
      }  while (validnumber == false);

      //we have the number, now lets play with it

      int lengthofnumber = new Integer(inputtednumber).toString().length();
      intasword = Integer.toString(inputtednumber);

      for (x = 1; x <= lengthofnumber; x++){
        //THIS IS WHERE I'M CONFUSED.  I Need to add the digits together.
        x++
      }
    }
}
 
Here it is in BASIC. Translate into the language of your choice. (I intentionally do not hav a compiler on my test machine.)

Sub FindNumbers()
a = 145
Dim b(10)
indx = 0
While a > 1
b(indx) = a Mod 10
a = a / 10
indx = indx + 1
Wend
For x = 0 To indx
c = c + b(x)
Next
End Sub


- Aunt Peggy
 
Last edited:
I don't see a way to do the same thing in Java, unfortunately.

It seems pulling a char out of a string is simple (String.charAt(x)), but pulling a digit out of a number??

Integer.digitAt(x) would be great. Don't see it tho.
 
Ok - I gave in and just decided to convert the number into a string, pulled out a char, then converted to a string and then to an int. Sucky way, but whatever, it works.

Still looking for any suggestions tho. What I put in the part above that says "Here's where I'm confused" is:

Code:
  for (x = 0; x < lengthofnumber; x++){
    charfornum = new Character(intasword.charAt(x)).toString();
    individualnumber = Integer.parseInt(charfornum);
    addedvalues= addedvalues + individualnumber;
  }

I feel dirty doing it that way.
 
You must use the mod (% in java) operator to pull out individual integers. If you remember using long division in school, you would end up with a remainder if you divided 145 by 10. Well, mod is remainder.

So, in the code I wrote, you have a while loop and within the while loop, you strip off each integer by taking the mod of your original number and store it into an array. In the first loop, 145 divided by 10 equals 14 with a remainder of 5. In the second loop, the fractional part is ignored, so 14 /10 is 1.4 with a remainder (mod) of 4.

So you have

Loop 1, a = 145, b(0) = 5, a = 14.5
Loop 2, a = 14.5, b(1) = 4, a = 1.45
Loop 3, a = 1.45, b(2) = 1, a = .145

The loop ends because a has become less than 1. The array b() now contains the digits in reverse order - 5, 4, 1.
 
The "correct" method is using mod.

Since you define the variable as an integer, it has no decimal place.

Divide (/)145 by 10 and you get 14.
Mod (%)145 by 10 and you get 5.
There's one digit.
Repeat as necessary.

And you can use a single variable for it.

int number;
int result=0;

// Enter the number somewhere...

while (number!=0){
result += number%10;
number /= 10;
}

System.out.print(result);
 
If you just want to sum the integers, simplify to :

a = 145
While a > 1
c = c + (a Mod 10)
a = a / 10
Wend
 
wow - I never caught on to the fact that dividing 145 by 10 leaves a remainder of 5. Makes sense, and I'll rewrite it to not be so cluttered.

Thanks!
 
wow - I never caught on to the fact that dividing 145 by 10 leaves a remainder of 5. Makes sense, and I'll rewrite it to not be so cluttered.

Thanks!
 
funny thing too - I had no idea you could use += and /= and so on. Makes it look much better than x = x + 1 like I always did in BASIC.

Rewriting that part too. Thanks for the help guys (and Aunt Peggy).
 
rpadula said:
Awww, there's never one correct way in software! I did a quick Google to see if there was a formula besides just using mod and found the following interesting thread:

http://www.thescripts.com/forum/thread222858.html

The most straightforward way to go is "mod."


-Rich

Hehe... exactly why i put it in quotes. I just figured that's what the professor was wanting ;)
 
Another shortcut you may want to use that you cannot in BASIC is post or pre increment:

a++ or ++a is the same as a=a+1
- Aunt Peggy
 
AuntPeggy said:
Another shortcut you may want to use that you cannot in BASIC is post or pre increment:

a++ or ++a is the same as a=a+1
- Aunt Peggy

Yeah, I use a++. Not sure what ++a does (have to look in my textbook).

Now I have a fun program to write. Gotta write a small guess the number game, with a mini AI. Woo!

In case anyone's curious - here's the final code for that last one.

Code:
import java.util.Scanner;

/* Written by Nick Brennan for CS152
 * 
 * This program will ask the user to enter a number between 1 and 1000
 * and check to make sure the number is within those bounds.
 * If the number is out of bounds, make fun of the user and ask for a
 * different number.
 * Then we calculate the sum of the digits in that number.
 */
public class Prog_5 {
	public static void main (String[] args){
		Scanner userinput = new Scanner (System.in);
		int inputtednumber;
		int x;
		int addedvalues = 0;
		boolean validnumber = false;
		
		do {
			System.out.println ("Please enter an integer between 1 and 1000: ");
			inputtednumber = userinput.nextInt();
			//I am assuming that by "in a loop" it was intended to use an if statement within a loop
			if (inputtednumber < 1 || inputtednumber > 1000){
				System.out.println ("Nah, I said between 1 and 1000!");
			} else {
				validnumber = true;
			}
		} while (validnumber == false);
		
		//we have the number, now lets play with it
		
		int lengthofnumber = new Integer(inputtednumber).toString().length();		
		
		for (x = 0; x < lengthofnumber; x++){
			addedvalues += inputtednumber % 10;
			inputtednumber /= 10;	
		}
		System.out.println ("Adding each individual digit together yields: " + addedvalues);

	}

}
 
a++ is post-increment
++a is pre-increment

It's a matter of when to save the new version of a.

a++ uses A, then increments it by one.
++a increments A, then uses it.

So if you had a=0
Print ++a -> 1
Print a++ -> 1
Print a -> 2

In the first one, a was incremented BEFORE it was used, so it prints out as 1, in the second, a was used THEN incremented, so it prints 1 out again. Then when printing a, you get 2.


For the record, I've never had a reason to use ++a ;)
 
neat. I don't see when I'd need that either, but its good to know :D

Funny thing is - one of the bugs I had in this stupid little baby program was that I couldn't figure out why my last loop was incrementing 2 times.

See - in basic, I'm used to adding the i++ at the end of the loop. In Java, it goes in the beginning. I had it in there both times. Fun.
 
Personally, I don't like combining ++ operations with any other operation. ++ is already an abbreviation for x=x+1, and if you start mixing in ++ with more complex formulae it becomes very difficult to read with no gain in performance at compilation/interpretation as far as I know.

y=++x*3 vs: x++;y=x*3 are the same thing, but the latter makes it much easier to trace exactly what's happening when reading it.

My opinion.

However, wrt the issue at hand, I'm with william on this one. Using mod is more correct than doing char conversions and parseInt. Not because one is wrong semantically, but because the multiple char conversion operations are much more inefficient than a single mathematical computation.
 
Greebo said:
Personally, I don't like combining ++ operations with any other operation. ++ is already an abbreviation for x=x+1, and if you start mixing in ++ with more complex formulae it becomes very difficult to read with no gain in performance at compilation/interpretation as far as I know.

y=++x*3 vs: x++;y=x*3 are the same thing, but the latter makes it much easier to trace exactly what's happening when reading it.

My opinion.

I agree, especially if you're unsure WHEN the variable is incrementing, better to just increment it by itself so you know that it will be the appropriate value after that line of code.
 
SkyHog said:
See - in basic, I'm used to adding the i++ at the end of the loop. In Java, it goes in the beginning. I had it in there both times. Fun.
Wait until you're switching between 4 languages at the same time doing end-to-end development...

I swear I started writing T-SQL statements with javascript code referring to the IE DOM once it was so bad...

And now MS SQL 2005 incorporates .NET into the core engine, so you can build .NET functions and call them from sprocs and sql statements. Things weren't confusing enough before!!! (Although being able to do real string manipulation inside SQL will be a nice plus... :) )
 
Code:
int lengthofnumber = new Integer(inputtednumber).toString().length();        
        
        for (x = 0; x < lengthofnumber; x++){
            addedvalues += inputtednumber % 10;
            inputtednumber /= 10;    
        }
        System.out.println ("Adding each individual digit together yields: " + addedvalues);

I must disagree with the above code. (Just noticed...)

You're still forcing the integer into a string and determining a "length".

The better idea is to simply run a while loop and reference inputtednumber be greater than 0.
 
wbarnhill said:
Code:
int lengthofnumber = new Integer(inputtednumber).toString().length();        
        
        for (x = 0; x < lengthofnumber; x++){
            addedvalues += inputtednumber % 10;
            inputtednumber /= 10;    
        }
        System.out.println ("Adding each individual digit together yields: " + addedvalues);

I must disagree with the above code. (Just noticed...)

You're still forcing the integer into a string and determining a "length".

The better idea is to simply run a while loop and reference inputtednumber be greater than 0.

Odd. I'll see if I can figure that out. That pretty much came directly from my teacher's mouth from the assignment:

"You might want to use another loop to calculate the final sum. If you for some reason would like to find the number of digits in the number, you could do that by converting the number to a String and checking the length. An example could be:

int x = 123;
int numLen = new Integer(x).toString().length();

would leave 3 in the variable numLen."
 
If you want the length of the number, the conversion is fine, but its unnecessary for the loop itself. It should always work the way you've done it, I can't think of a case where you could get the length wrong and over-loop - but it does add that extra variable to the equation.
 
Have I mentioned, btw, how much I love programming?

The sense of accomplishment, even on a stupid simple program like this is amazing (I had written 5 other programs before this tonight for the class with no problems, and felt amazing all night long).

A while ago, I used to be big on the VisualBasicForums.com forums, helping people with basic VB6 questions and stuff. We used to have coding challenges monthly, and it was a blast. I need to get back into that. I am sure that writing a program that loops ASCII art on a screen or finding the powers of numbers without using an exponent method is gonna get old quickly :D
 
SkyHog said:
Have I mentioned, btw, how much I love programming?

Great. I have a huge project for work that I need to get done. This is what I've written so far:

Code:
<?php

?>

Can you have it done by Friday?
 
jangell said:
Great. I have a huge project for work that I need to get done. This is what I've written so far:

Code:
<?php

?>

Can you have it done by Friday?

Sure thing:

Code:
<?php
echo 'hello world, yo!';
?>

Do I get paid for this?
 
Code:
<?php
 
?>
Who can improve on that perfectly bug-free code?
- Aunt Peggy
 
SkyHog said:
Sure thing:

Code:
<?php
echo 'hello world, yo!';
?>
Do I get paid for this?
No, you didn't ask to be before finishing.
 
ahh - the magic secret to programming - never finish before talking turkey :D
 
AuntPeggy said:
Code:
<?php
 
?>
Who can improve on that perfectly bug-free code?
- Aunt Peggy


I can. Turn on the short_open_tag option in php.ini, and write:

Code:
<?
?>

You can also enable asp_tags, and if you're coming from ASP, write this in PHP, validly:

Code:
<%  
%>
 
I used to be hell on wheels with PASCAL. Does anyone care?

Didn't think so!
 
SCCutler said:
I used to be hell on wheels with PASCAL. Does anyone care?

Didn't think so!

Borland Turbo Pascal; still have the manuals on the shelf in the garage, and the 5.25" install floppies... why??!?!

Sure enjoyed that language! Worked with it all the way through Delphi 2.0.
 
Troy Whistman said:
Borland Turbo Pascal; still have the manuals on the shelf in the garage, and the 5.25" install floppies... why??!?!

Sure enjoyed that language! Worked with it all the way through Delphi 2.0.
Oh, yeah... BTDT ... and then moved "up"? to turbo Ada on a dual 5.25 floppy IBM (genuine, not clone) [strikeout]386[/strikeout] edit: 8088 pc ... whooo hooo!!!
 
Last edited:
gkainz said:
Oh, yeah... BTDT ... and then moved "up"? to turbo Ada on a dual 5.25 floppy IBM (genuine, not clone) 386 pc ... whooo hooo!!!
386? Pshh.

Lobo Max Z-80, two 5.25" floppies, with BASIC baby. YEAH.

Oh and a dot matrix printer that would wake the neighbors.

Then came the 286, then the 486 (On which I learned to program C++ with Borland's DOS setup), then we got behind on technology until 1995 and my father installed a Pentium Overdrive chip on the 486... then I bought a Cyrix (I had a more vulgar name for it..) 333Mhz machine which had the uncanny ability to reboot anytime I was doing something important. Then a Compaq Presario 1235 266 AMD K-6 laptop (Oh yeah, livin large), then my father's 400Mhz Pentium II, then my 1.4 Ghz P4 that I got for graduation, then my current system which I built in 2004 and needs to be upgraded.

Ah, technological progression.
 
Last edited:
Built a Z-80 based S-100 system. Kits from Jade Computer.

Then onto a Heath/Zenith Z-100 (that's still in the garage) - I homebrewed the drive controller.

Got an IBM XT286 as the next machine, a whole 20 mB of hard drive. Invested in Turbo Pascal and the toolboxes (ran with that all the way through Delphi). Also got Turbo C and Turbo C++. I think there's a Fortran compiler in a box here somewhere, too.

Various machines after that, most all homebuilt, except the laptops.
 
oops ... my brain didn't follow the right symbolic link ... that IBM PC was an 8088 ...
 
wsuffa said:
Got an IBM XT286 as the next machine, a whole 20 mB of hard drive.

Oh yeah, the 20MB hard drives that were the size of two 5.25" bays. :D
 
wbarnhill said:
Oh yeah, the 20MB hard drives that were the size of two 5.25" bays. :D

Ah, yes... before IDE and EIDI and SCSI, we had MFM and RLL hard drives! Big heavy mothers...
 
Still got the Timex-Sinclair 1000 and Flight Simulator on a cassette tape! Also with 8K (yep- K) of RAM! I had to turn down an offer of a PDP-8 when I was a grad student (no place to keep it).
 
Back
Top