Jump to content

Another Quick Java Question


Recommended Posts

In class we've been working on loop statements and as part of my homework (this is the only part I don't have done) is to be able to take the odd numbers within a number (so say the number is 32677, take the odd numbers) and add them together (so it would be 17). Maybe I'm just having a brain fart, but I just can't think of how to write this code.

 

Thanks!

Finally on here to update that I have officially quit! It's been fun.
[hide=Signature]
Gandalf14141.png
R.I.P Billy Mays and <3 My Friend C.D.S 7/8/09 <3
60,816th to 99 Fletching 03/07/09|220,309th Person to be Able to Kill Dusties 10 Year Cape on 12/20/14[/hide]

grammar2gr8dx.png

Link to comment
Share on other sites

Last time you posted, I showed you how to isolate the last digit in an integer. So you want to remove the last digit from the integer each iteration, check if it's odd, and add it to the sum if it is.

 

while(input > 0){
t = input%10;
if(t%2==1){sum+=t;}
input /= 10;
}

 

That's the necessary part in C++. You should be able to figure it out from there.

Link to comment
Share on other sites

That is actually a neat way of doing it, Meredith.

 

The Java equivalent of the above:

int number=1234567,sum=0,trimmed;
while(number!=0){
   sum+=(trimmed=number%10)%2==1?trimmed:0;
   number/=10;
}
System.out.println(sum);

 

Isn't a whole lot different then yours. :P.

 

 

He could, however, use Scanner in which his entire project is only a few lines:

int sum=0,trimmed;
Scanner number=new Scanner(System.in).useDelimiter("");  
System.out.print("Enter an integer: ");  
while(number.hasNextInt()){sum+=(trimmed=number.nextInt())%2==1?trimmed:0;}   
System.out.println("The sum of the odd integers is: "+sum);

Gets the input and outputs the sum. :P.

09144a99bb.png

Link to comment
Share on other sites

Thanks for the help guys, I appreciate it!

Finally on here to update that I have officially quit! It's been fun.
[hide=Signature]
Gandalf14141.png
R.I.P Billy Mays and <3 My Friend C.D.S 7/8/09 <3
60,816th to 99 Fletching 03/07/09|220,309th Person to be Able to Kill Dusties 10 Year Cape on 12/20/14[/hide]

grammar2gr8dx.png

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.