Java中获取用户输入值的四种方法

来源:互联网 发布:wow7.0装备数据库 编辑:程序博客网 时间:2024/05/01 09:08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
importjava.io.BufferedReader; 
importjava.io.IOException; 
importjava.io.InputStreamReader; 
importjava.util.Scanner; 
  
publicclass EnterTest {
    
  publicstatic void main(String[] args) { //主方法
    CharTest(); //调用System.in方法
    ReadTest(); //调用ReadTest方法
    ScannerTest();//调用ScannerTest方法
  }
  /**
   * System.in和System.out方法
   * 缺点一: 该方法能获取从键盘输入的字符,但只能针对一个字符的获取
   * 缺点二: 获取的只是char类型的。如果想获得int,float等类型的输入,比较麻烦。
   */
  publicstatic void CharTest(){ 
    try{
      System.out.print("Enter a Char:");
      chari = (char)System.in.read();
      System.out.println("Yout Enter Char is:" + i);
    }
    catch(IOException e){
      e.printStackTrace();
    }
      
  }
  /**
   * InputStreamReader和BufferedReader方法
   * 优点: 可以获取键盘输入的字符串
   * 缺点: 如何要获取的是int,float等类型的仍然需要转换
   */
  publicstatic void ReadTest(){
    System.out.println("ReadTest, Please Enter Data:");
    InputStreamReader is = newInputStreamReader(System.in); //new构造InputStreamReader对象
    BufferedReader br = newBufferedReader(is); //拿构造的方法传到BufferedReader中
    try{//该方法中有个IOExcepiton需要捕获
      String name = br.readLine();
      System.out.println("ReadTest Output:" + name);
    }
    catch(IOException e){
      e.printStackTrace();
    }
      
  }
  /**
   * Scanner类中的方法
   * 优点一: 可以获取键盘输入的字符串
   * 优点二: 有现成的获取int,float等类型数据,非常强大,也非常方便;
   */
  publicstatic void ScannerTest(){
    Scanner sc = newScanner(System.in);
    System.out.println("ScannerTest, Please Enter Name:");
    String name = sc.nextLine();  //读取字符串型输入
    System.out.println("ScannerTest, Please Enter Age:");
    intage = sc.nextInt();    //读取整型输入
    System.out.println("ScannerTest, Please Enter Salary:");
    floatsalary = sc.nextFloat(); //读取float型输入
    System.out.println("Your Information is as below:");
    System.out.println("Name:"+ name +"\n"+ "Age:"+age + "\n"+"Salary:"+salary);
  }
}
方法四:定义一个新类,如GameHelper,代码如下:

import java.io.*;

class GameHelper{

public StringgetUserInput (Stringprompt) {

String inputLine = null;

System.out.print(prompt+ " ");

try {

BufferedReader is =new BufferedReader(

new InputStreamReader(System.in));

inputLine = is.readLine();

if (inputLine.length()==0) return null;

} catch(IOException e){

System.out.println("IOException: "+ e);

}

return inputLine;

}

}

主程序代码如下:
GameHelper helper=new GameHelper();
String test = helper.getUserInput("enter a number");//通过class里定义的getUserInput方法获取用户的值


注:前三种方法为转载他人URL:http://www.jb51.net/article/67718.htm
0 0
原创粉丝点击