JAVA的输入

Posted suxinpaul

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

以上是关于JAVA的输入的主要内容,如果未能解决你的问题,请参考以下文章

java 用户输入格式错误 重新输入的方法

java怎么 输入输出中文

java 输入数字 输出英文

java如何在输入框中判断是不是输入的是数字?

java Zip压缩输入输出流问题

java中判断输入的是不是是整数