The Artima Developer Community
Sponsored Link

Java Answers Forum
Assign digits in an integer to separate variables

2 replies on 1 page. Most recent reply: Sep 3, 2009 1:00 AM by Vincent O'Sullivan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Marc Hammond

Posts: 1
Nickname: mhammond76
Registered: Aug, 2009

Assign digits in an integer to separate variables Posted: Aug 29, 2009 9:24 AM
Reply to this message Reply
Advertisement
How can I assign a variable to each digit in a 4-digit integer. For example, suppose the user enters 1234, I want to assign a = 1, b = 2, c = 3, and d = 4.


Kondwani Mkandawire

Posts: 530
Nickname: spike
Registered: Aug, 2004

Re: Assign digits in an integer to separate variables Posted: Sep 2, 2009 11:18 PM
Reply to this message Reply
> How can I assign a variable to each digit in a 4-digit
> integer. For example, suppose the user enters 1234, I want
> to assign a = 1, b = 2, c = 3, and d = 4.

Off the top of my head:

1) Convert the Integer into a String.
String str = ""+1234;

2) Tokenize str. - jeez, not sure if you can use StringTokenizer. Else you can just use charAt and a loop going through the String.
int [] myVars = new int[str.length()];
int index = 0;
for (index = 0; index < str.length(); index++) {
    myVars[index] = new Integer(""+str.charAt(index));
}


now your array has assigned myVars[0] = 1, myVars[1] = 2, etc...

I'm not sure if the first place is taken by the empty String you may have to check against that... i.e. myVars[0] might actually be "", meaning you'll have to skip it...

There is probably an easier way, anyone please?

Vincent O'Sullivan

Posts: 724
Nickname: vincent
Registered: Nov, 2002

Re: Assign digits in an integer to separate variables Posted: Sep 3, 2009 1:00 AM
Reply to this message Reply
byte[] b = new String(""+1234).getBytes();
That's about as simple as I can think of.

Flat View: This topic has 2 replies on 1 page
Topic: please help me.. Previous Topic   Next Topic Topic: Unix utility

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use