Java控制台输入输出

控制台输入

1、Scanner实现

import java.util.Scanner;

/**A simple text scanner which can parse primitive types and strings using
* regular expressions.
*/

Scanner sca = new Scanner(System.in); //以System.in为输入流创建Scanner

//获取控制台输入的字符串(回车后sca会获取控制台输入的值)
String input=sca.next(); //封装了18种next***方法,可更加实际情况灵活应用

.... //业务处理

2、BufferedReader实现

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//以System.in为输入流创建BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str = null;
try {

  //获取控制台输入的字符串(回车后br会获取控制台输入的整行字符串值)
//必须捕获IO异常

    str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}

.... //业务处理

控制台输出

//输出制定数据后自动换行
System.out.printlin();

  详细解释:
     /**
* Terminates the current line by writing the line separator string.
*/

public void println();

    /**
* Prints a boolean and then terminate the line.
*/

public void println(boolean x);

    /**
* Prints a character and then terminate the line.
*/

public void println(char x);

    /**
* Prints an integer and then terminate the line.
*/

public void println(int x);

    /**
* Prints a long and then terminate the line.
*/

public void println(long x);

    /**
* Prints a float and then terminate the line.
*/

public void println(float x);

    /**
* Prints a double and then terminate the line.
*/
    public void println(double x);

    /**
* Prints an array of characters and then terminate the line.
*/

public void println(char x[]);

    /**
* Prints a String and then terminate the line
*/

public void println(String x);

    /**
* Prints an Object and then terminate the line.
*/

public void println(Object x);

//输出制定数据后不换行
System.out.print(String x
); //同println,但无无参数(只是换行)的重载


如果给你带来帮助,欢迎微信或支付宝扫一扫,赞一下。