Jump to content

Easy Java Help Needed

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
SafiMoyo

SafiMoyo

    Newbie

  • Members
  • Pip
  • 2 posts
So I'm writing a program to read an input, and kind of break it up. Like, it reads a single input (Example: 20080402) then breaks it up, and redisplays it (4/2/2008). What I want to do is separate the input into three variables, then I can take it from there... But I don't know how to split an input or variable up.

#2
Turk4n

Turk4n

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,847 posts

SafiMoyo said:

So I'm writing a program to read an input, and kind of break it up. Like, it reads a single input (Example: 20080402) then breaks it up, and redisplays it (4/2/2008). What I want to do is separate the input into three variables, then I can take it from there... But I don't know how to split an input or variable up.

You should use stringtokenizer !
StringTokenizer (Java 2 Platform SE v1.4.2)

Good Luck !
Posted Image

#3
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
Either use a StringTokenizer like Turk4N said or you can use the scanner class as well.

Scanner (Java 2 Platform SE 5.0)

#4
JerrySpock

JerrySpock

    Newbie

  • Members
  • Pip
  • 9 posts
You could also use String.substring.

java.sun.com/javase/6/docs/api/java/lang/String.html#substring(int,%20int)


String string = "20090112";

String date;


date += string.substring(4,5) + "-";  // date is "01-"

date += string.substring(6,7) + "-";  // date is "01-12-"

date += string.substring(0.3);       // date is "01-12-2009"


Or if you had tokens between the numbers, then you could also use String.split.

java.sun.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)

StringTokenizer is easy to use, but just so you know, according to the API,

Quote

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.