[ Java ] Useful methods to save time.

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
Spike
New poster
Posts: 29
Joined: Mon Mar 18, 2002 2:00 am
Location: Washington State
Contact:

[ Java ] Useful methods to save time.

Post by Spike » Fri Aug 30, 2002 12:47 am

Being a JAVA programmer on UVA can be very frustrating, can't it? Well, I created some methods to help myself out and I felt I'd share 'em. I know they're pretty basic, but hey, it might help some of you.


METHODS FOR USING STANDARD IN
notice the "percent" before the numbers... Tribute to C
[java]

/* reads a float as the next token of a file */
/* returns NaN if number is not valid */
static float percentFloat(){
String s = token();
if( s == null ) return Float.NaN;
try{
Float f = new Float( s );
return f.floatValue();
}catch( Exception e ){}
return Float.NaN;
}


/* reads a float as the next token of a file */
/* returns NaN if number is not valid */
static double percentDouble(){
String s = token();
if( s == null ) return Double.NaN;
try{
Double d = new Double( s );
return d.doubleValue();
}catch( Exception e ){}
return Double.NaN;
}

/* reads a long as the next token of a file */
/* since Long has no NaN, I return MIN_VALUE if not valid */
static long percentLong(){
String s = token();
if( s == null ) return Long.MIN_VALUE;
try{
Long l = new Long( s );
return l.longValue();
}catch( Exception e ){}
return Long.MIN_VALUE;
}


/* reads an int as the next token of a file */
/* since Integer has no NaN, I return MIN_VALUE if not valid */
static int percentInt(){
String s = token();
if( s == null ) return Integer.MIN_VALUE;
try{
Integer i = new Integer( s );
return i.intValue();
}catch( Exception e ){}
return Integer.MIN_VALUE;
}


/* read line from stdIn by using \n as delim */
static String readLine(){return token( "\n\r" );}


/* read token from stdIn with standard delims */
static String token( ){return token( " \n\r\t" );}


/* read token from stdIn with custom delims */
/* returns null for end of file or any exceptions */
static String token( String delim ){
char c = delim.charAt(0);
StringBuffer s = new StringBuffer("");
try{
while( delim.indexOf( (int) c ) != -1 && c != 65535 )
c = (char) System.in.read();
while( delim.indexOf( (int) c ) == -1 && c != 65535 ){
s.append( (char) c );
c = (char) System.in.read();
}
}catch( Exception e ){ return (null); }
if( s.toString().equals("") ) return null;
return s.toString();
}
[/java]

Please post a response if you found these at all useful.
Last edited by Spike on Tue Dec 17, 2002 11:24 am, edited 1 time in total.

Spike
New poster
Posts: 29
Joined: Mon Mar 18, 2002 2:00 am
Location: Washington State
Contact:

In Addition... parsing non-Integers

Post by Spike » Fri Aug 30, 2002 12:54 am

Although Double.parseDouble() is supposed to be a part of JAVA since 1.2, it doesn't appear to be available in UVA. Here's what I do instead...


I create a Double object and then convert to double:

[java]
String string$ = "1245.623";
double x = ( Double.valueOf( string$ ) ).doubleValue();

[/java]

Floats and Longs can be used in similar fashion.

Spike
New poster
Posts: 29
Joined: Mon Mar 18, 2002 2:00 am
Location: Washington State
Contact:

When blank Lines matter

Post by Spike » Fri Dec 06, 2002 11:48 pm

When blank lines mattter, use the following...
[java]
static String readLine(){
String delims = "\n";
char c = delim.charAt(0);
StringBuffer s = new StringBuffer("");
try{
c = (char) System.in.read();
while( delim.indexOf( (int) c ) == -1 && c != 65535 ){
if( c != '\r' ) s.append( (char) c );
c = (char) System.in.read();
}
}catch( Exception e ){ return (null); }
if( s.toString().equals("") ) return null;
return s.toString();
}[/java]

Eric____
New poster
Posts: 8
Joined: Thu Jan 30, 2003 10:13 am
Contact:

Post by Eric____ » Tue Feb 11, 2003 1:14 pm

i used to use SavitchIn
yeah, this is helpful to me. thankyou.

zacharyleung
New poster
Posts: 14
Joined: Tue Feb 03, 2004 3:43 am

Post by zacharyleung » Tue Feb 03, 2004 3:28 pm

Just wondering, what is the significance of the number 65535 in this line?

[java]
while( delim.indexOf( (int) c ) != -1 && c != 65535 )
[/java]

Thanks.

cobrahc
New poster
Posts: 2
Joined: Mon May 17, 2004 11:28 pm

Post by cobrahc » Mon May 17, 2004 11:33 pm

wow..
thats help me a lot
thanx

boyeric
New poster
Posts: 6
Joined: Sun Jun 20, 2004 5:08 pm

Great Job!

Post by boyeric » Sun Jun 20, 2004 5:13 pm

great job!
what could i say, nobody knows how frustrated i used to be facing inputs...
thanx a lot!

Maniac
Experienced poster
Posts: 105
Joined: Tue Oct 14, 2003 3:24 pm
Location: Utrecht, Holland

Post by Maniac » Thu Aug 12, 2004 1:48 pm

Here's the class I always start with when I start working on a new problem:

[java]
// @JUDGE_ID: XXXXXX PROBLEMNUMBER Java

import java.util.*;
import java.io.*;

class Main {
static StringTokenizer tok;

static String readLine () { //no buffer-size needed :-)
StringBuffer s = new StringBuffer();
int car;
boolean nochars = true;
try {
while(true) {
car = System.in.read();
if (car < 0 || car == '\n') break;
else if(car != '\r') {
s.append((char) car);
nochars = false;
}
}
} catch (IOException e) { return null; }

if (car < 0 && nochars) return null;
return s.toString();
}

static void write(String s) {
System.out.print(s);
}

static String nextToken() throws Exception {
while(tok == null || !tok.hasMoreTokens())
tok = new StringTokenizer(readLine());
return tok.nextToken();
}

static int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}

static double nextDouble() throws Exception {
return Double.valueOf(nextToken()).doubleValue();
}

public static void main(String[] args) throws Exception {
// solve runs untill EOF for example
String line = readLine();
int run = 1;
while(line != null && line.length() > 0) {
doit(run++);
line = readLine();
}
}

static int global_var; //global variables must be static

static void doit(int run) throws Exception {
// solve run
String result = "The answer is 4\n";
write(result);
}
}
[/java]

good luck!

randomtaiwanese
New poster
Posts: 32
Joined: Fri Oct 01, 2004 10:53 pm

Post by randomtaiwanese » Mon Nov 15, 2004 10:09 am

Maniac wrote:Here's the class I always start with when I start working on a new problem:

[java]
// @JUDGE_ID: XXXXXX PROBLEMNUMBER Java

import java.util.*;
import java.io.*;

class Main {
static StringTokenizer tok;

static String readLine () { //no buffer-size needed :-)
StringBuffer s = new StringBuffer();
int car;
boolean nochars = true;
try {
while(true) {
car = System.in.read();
if (car < 0 || car == '\n') break;
else if(car != '\r') {
s.append((char) car);
nochars = false;
}
}
} catch (IOException e) { return null; }

if (car < 0 && nochars) return null;
return s.toString();
}

static void write(String s) {
System.out.print(s);
}

static String nextToken() throws Exception {
while(tok == null || !tok.hasMoreTokens())
tok = new StringTokenizer(readLine());
return tok.nextToken();
}

static int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}

static double nextDouble() throws Exception {
return Double.valueOf(nextToken()).doubleValue();
}

public static void main(String[] args) throws Exception {
// solve runs untill EOF for example
String line = readLine();
int run = 1;
while(line != null && line.length() > 0) {
doit(run++);
line = readLine();
}
}

static int global_var; //global variables must be static

static void doit(int run) throws Exception {
// solve run
String result = "The answer is 4\n";
write(result);
}
}
[/java]

good luck!
seeme like the standard one uses more primitive methods... aka should be faster...
is yours any fast??

Maniac
Experienced poster
Posts: 105
Joined: Tue Oct 14, 2003 3:24 pm
Location: Utrecht, Holland

Post by Maniac » Mon Nov 15, 2004 11:29 am

fast enough to use as a standard template! What do you mean is it fast enough? reading input is very rarely the bottle-neck when solving a problem...

h_s_potter2002
New poster
Posts: 6
Joined: Fri Nov 12, 2004 2:33 am

Post by h_s_potter2002 » Sun Nov 28, 2004 6:51 pm

Can someone show me some java code for reading the input file below using the OP's java methods? I don't exactly understand how I would use it.




Code: Select all

2 7
3 5
It doesn't matter whether the numbers go into an array, or anything, I just want to see them being read as ints. And btw, this is for a USACO program.

Darko
Guru
Posts: 580
Joined: Fri Nov 11, 2005 9:34 am
Location: Calgary, Canada

Post by Darko » Fri Nov 11, 2005 9:58 am

(edit - well, my post was the last one in here, so here's something that might be useful to someone)

I almost lost my mind doing 10137 - The Trip. It got accepted the way it was at PC, but not here. In the end, i changed the line:

Code: Select all

double mean = Math.round(totalSpent/n);
to:

Code: Select all

double mean = (long)(totalSpent/n + 0.5);
and it worked?!?!? sigh... (note that I multiplied all values by 100 while reading them in, that is why "rounding to 2 decimals" involves only longs).

Btw, doc for Math.round(x) says that it is just Math.floor(x+0.5). I did try that among several other things. I am really confused. I guess I should install gcc 2.95 somewhere or something.

Darko

MAK
New poster
Posts: 28
Joined: Sun Oct 23, 2005 3:44 pm
Location: Dhaka, Bangladesh

Thanks

Post by MAK » Sun Jan 01, 2006 11:33 am

I had the same problem and after trying many times gave up at this OJ although I got AC at programming-challenges.com. I'll try you technique now, thanks!

Post Reply

Return to “Java”