现在的位置: 首页 > 综合 > 正文

java 使用Scanner獲取鍵盤輸入

2013年10月11日 ⁄ 综合 ⁄ 共 1352字 ⁄ 字号 评论关闭

package yong.crazy;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * 使用Scanner獲取鍵盤輸入 (默认UTF-8)
 * Scanner是一個基于正則表達式的文本掃描器,它可以從文件、輸入流、字符串中解析出基本類型值和字符串值
 * 主要方法:hasNextXxx(); 是否還有下一項    nextXxx();獲得下一個輸入項。
 * @author root
 *
 */

public class TestScanner {

    /**
     * @param args
     * @throws FileNotFoundException
     */
    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);    //System.in代表標准輸入,就是鍵盤輸入
//        sc.useDelimiter("/n");    //把回車符作為分隔符   reset();取消
       
       
        System.err.println("輸入整數:" + sc.nextInt());        //獲得輸入的整數
        System.out.println("輸入雙精度:" + sc.nextDouble());    //獲得輸入的雙精度
        System.out.println("輸入字符串:" + sc.next());        //獲得輸入字符串
        System.out.println("獲得一行數據:" + sc.nextLine());    //獲得輸入一行數據

        Scanner scFile = new Scanner(new File("a.txt"));
        System.err.println("a.txt文件内容如下:");
        while (scFile.hasNextLine())    //读取文件内容
        {
            System.out.println(scFile.nextLine());
        }
       
        //判斷是否還有下一項(字符串)
        while (sc.hasNext())
        {
            System.out.println("鍵盤輸入的字符串內容是:" + sc.next());
        }
    }
}

//特别注意的是JDK5.0以前的版本不能这样处理,这多少有些令人沮丧,还好我们用swing包里的方法也不难实现,只需把构造函数里的内容改为如下即可:
//
//    this.name = JOptionPane.showInputDialog("Name?");
//    String input = JOptionPane.showInputDialog("AGE?");
//    this.age = Integer.parseInt(input);
//  
//当然,别忘了导入swing包:
//    import javax.swing.*;

抱歉!评论已关闭.