J2SE 1.5 Formatted Input Question

M

Matt

If we have input Joe 25 in command line, then we are able to parse it
by following code:

Scanner s = new Scanner(System.in);
String name = s.next();
String age = s.nextInt();
s.close();


However, what if the input is 10:25:33? Are we able to parse it like
sscanf in C? Like the following C code?

char* buf = "10:25:33";
sscanf(buf, "%d:%d:%d", &h, &m, &s);

Please advise. thanks!!
 
R

Real Gagnon

However, what if the input is 10:25:33? Are we able to parse it like
sscanf in C? Like the following C code?

char* buf = "10:25:33";
sscanf(buf, "%d:%d:%d", &h, &m, &s);

Please advise. thanks!!

import java.util.*;

class TestScanner {
public static void main(String args[]) {
String input = "10:11:12";
Scanner sc = new Scanner(input).useDelimiter(":");
while (sc.hasNextLong()) {
int i = sc.nextInt();
System.out.println(i);
}
}
}


Bye.
 
E

Eric Reitmaier

However, what if the input is 10:25:33? Are we able to parse it like
sscanf in C? Like the following C code?

char* buf = "10:25:33";
sscanf(buf, "%d:%d:%d", &h, &m, &s);

Please advise. thanks!!

I guess you will work with date/time data, why don't use SimpleDateFormat?
(In this example it is started from Jan 01 1970)

import java.text.SimpleDateFormat;
import java.util.*;

public class DateFormatTest {

public static void main(String[] cmdArgs) throws Exception {
String input = "10:25:33";

SimpleDateFormat sdfInput = new SimpleDateFormat("hh:mm:ss");
Date date = sdfInput.parse(input);
System.out.println(date);
}
}

$ java DateFormatTest
Thu Jan 01 10:25:33 MET 1970

-
Eric
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top