java 方法 示例
Here is the some of the popular ways to take input from the user in Java,
这是一些使用Java从用户那里获取输入的流行方法 ,
By Using BufferedReader Class
通过使用BufferedReader类
By Using Console Class
通过使用控制台类
By Using Scanner Class
通过使用扫描仪类
1) Example of user input using BufferedReader
1)使用BufferedReader的用户输入示例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
// Create an object of BufferedReader rdr
BufferedReader rdr =
new BufferedReader(new InputStreamReader(System.in));
// Display message for user
System.out.print("Enter your Job: ");
// BufferedReader object rdr read input from standard input stream
// and wrapped in BufferedReader
String job = rdr.readLine();
System.out.println("You are a " + job);
}
}
Output
输出量
Enter your Job: Technical writer
You are a Technical writer
2) Example of user input using Console class
2)使用Console类的用户输入示例
public class Main {
public static void main(String[] args) {
// Display message for user
System.out.print("Enter your Job: ");
// Using Console class to take input from user
String job = System.console().readLine();
System.out.println("You are a " + job);
}
}
Output
输出量
Enter your Job: Technical writer
You are a Technical writer
3) Example of user input using Scanner class
3)使用Scanner类的用户输入示例
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
// Display message for user
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.println("My name is " + name);
// Display message for user
System.out.print("Enter your MCA percent: ");
float per = input.nextFloat();
System.out.println("My percent in MCA is: " + per);
}
}
Output
输出量
Enter your MCA percent: 98
My percent in MCA is: 98.0
翻译自: https://www.includehelp.com/java/different-ways-to-take-input-from-the-user-in-java.aspx
java 方法 示例