Java代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class MainClass
{
public static void method1()
{
//使用Scanner
Scanner scanner=new Scanner(System.in);
System.out.print("Please input a number:");
int num=scanner.nextInt(); //获取整数值
System.out.println("The number you input is:"+num);
System.out.println("----------------------------");
System.out.print("Please input some character:");
String str=scanner.next(); //获取字符串值
System.out.println("The string you input is:"+str);
}
public static void method2()
{
//使用BufferedReader
try
{
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please input a number:");
String str=reader.readLine(); //获取字符串
System.out.println("The number you input is:"+str);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
个人比较喜欢第一种方法,简单。第二种方法使用readLine()方法返回值是String类型。如果想获取int或float类型,则自己需要写类型转换函数进行转换。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class MainClass
{
public static void method1()
{
//使用Scanner
Scanner scanner=new Scanner(System.in);
System.out.print("Please input a number:");
int num=scanner.nextInt(); //获取整数值
System.out.println("The number you input is:"+num);
System.out.println("----------------------------");
System.out.print("Please input some character:");
String str=scanner.next(); //获取字符串值
System.out.println("The string you input is:"+str);
}
public static void method2()
{
//使用BufferedReader
try
{
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please input a number:");
String str=reader.readLine(); //获取字符串
System.out.println("The number you input is:"+str);
} catch (IOException e)
{
e.printStackTrace();
}
}
}
个人比较喜欢第一种方法,简单。第二种方法使用readLine()方法返回值是String类型。如果想获取int或float类型,则自己需要写类型转换函数进行转换。