Two basic input methods in Java

1. Use the Scanner class

Requires java.util package

Construct an object of the Scanner class, attached to the standard input stream System.in , and then obtain input through its methods.

Commonly used methods: nextLine(); (string), nextInt(); (integer), nextDouble(); (double) and so on.

Use the close(); method to close the object at the end.

example:

import java.util.*;

class IOTest {
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		System.out.println("enter your name:");
		String name = sc.nextLine();
		System.out.println("enter your age:");
		int age = sc.nextInt();
		System.out.println("enter your occupation:");
		String occ = sc.next();
		System.out.println("name:" + name + "\n" + "age:" + age + "\n" + "occupation:" + occ);
		sc.close();
	}
}

输入:
enter your name:
g28
enter your age:
20
enter your occupation:
student
输出:
name:g28
age:20
occupation:student

2. Use the System.in.read(); method

Requires the java.io package.

System.in gets the data from the annotation input, the data type is InputStream. The ASCII code is returned by the read(); method. If the return value is -1, it means that no character has been read to end the work.


When using, you need to add a throw statement or surround it with try/catch.

example:

import java.io.*;

class IOTest {
	public static void main(String args[]) {
		int c;
		System.out.println("please enter the string:");
		try {
			while((c = System.in.read()) != -1)
				{
					System.out.print((char)c); 
				}
		} catch (IOException e) {
			System.out.println(e.toString());
		}
	}
}

输入:
please enter the string:
My name is g28.
输出:
My name is g28.


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324092745&siteId=291194637