JAVA的输入

How do I scanf, readln, etc. in Java?

JAVA 没有C语言的scanf()、fscanf()、sscanf(),也没有Pascal的read()、readln(),也没有Fortran的READ()。我们可以用DataInputStream.readline()和BufferedReader()

使用StringTokenizer分离字符串

Java has no exact equivalent to C's scanf(), fscanf() andsscanf() functions, Pascal'sread() and readln() function, or Fortran'sREAD* 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 scattered across several classes. You first read an input line into aString usingDataInputStream.readline() or BufferedReader (in Java 1.1)

Next use the StringTokenizer class in java.util to split the String into tokens. By defaultStringTokenizer splits on white space (spaces, tabs, carriage returns and newlines), but this is user definable.

For example,

 

prints the following output:
import java.util.StringTokenizer;

public class STTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s="9 23 45.4 56.7";
		StringTokenizer st=new StringTokenizer(s);
		while(st.hasMoreTokens())
		{
			System.out.println(st.nextToken());
		}
	}

}
Finally you convert these tokens into numbers using the type wrapper classes as described in the next question.

How do I convert strings to numbers?

public class ConvertTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String 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=Double.valueOf(str).doubleValue();
		System.out.println(d);
		
	}

}


字符串转换成数字

You can convert strings into numbers using the Integer, Float, Double and Long type wrapper classes as indicated by the following code snippet:

 

There are no equivalent Short and Byte classes in Java 1.0. There are in Java 1.1. For shorts and bytes use the Integer class but use the byteValue() or shortValue() methods instead.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值