You are on page 1of 1

UNKNOWN //************************************** // Name: How do I scanf, readln,

etc. in Java? // Description:Java has no exact equivalent to C's scanf(), fscan


f() and sscanf() functions, Pascal's read() and readln() function, or Fortran's
READ* function. In particular there's no one method that lets you get input from
the user as a numeric value. However, roughly equivalent functionality is scatt
ered across several classes. You first read an input line into a String using Da
taInputStream.readline() or BufferedReader (in Java 1.1) Next use the StringToke
nizer class in java.util to split the String into tokens. By default StringToken
izer splits on white space (spaces, tabs, carriage returns and newlines), but th
is is user definable. (Found on the web--Java FAQ--http://sunsite.unc.edu/javafa
q/javafaq.html) // By: // // // Inputs:None // // Returns:None // //Assumes:prin
ts the following output: 9 23 45.4 56.7 // //Side Effects:None //***************
*********************** import java.util.StringTokenizer;class STTest { public s
tatic void main(String args[]) { String s = "9 23 45.4 56.7"; StringTokenizer st
= new StringTokenizer(s);while (st.hasMoreTokens()) { System.out.println(st.nex
tToken());} } } Finally you convert these tokens into numbers using the type wra
pper classes class ConvertTest { public static void main (String args[]) { Strin
g str; str = "25"; int i = Integer.valueOf(str).intValue(); System.out.println(i
); long l = Long.valueOf(str).longValue(); System.out.println(l); str = "25.6";
float f = Float.valueOf(str).floatValue(); System.out.println(f); double d = Dou
ble.valueOf(str).doubleValue(); System.out.println(d); } }

You might also like