zoukankan      html  css  js  c++  java
  • java基本输入输出练习

        java获取用户的输入分两种,一种是字符的输入,一种是整行的输入,要用到java.io包。对于字符输入来说,使用System.in方法可以输入字符;对于整行的输入,可以使用Scanner类的方法获取整行输入。

    import java.io.*;
    import java.util.*;
    public class helloWorld {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            char c = '3';
            System.out.print("hello world,please read in a character:");
            try{
                //只能读取输入的一个字母
                c=(char)System.in.read();
            }catch(IOException e){}
            System.out.println("entered:" + c);        
            String s = "";
            System.out.println("please read in a line:");
            //读取输入的一行
            //BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            Scanner in = new Scanner(System.in);
            s = in.next();
            System.out.println("entered" + s);        
            }
    }

        Scanner是一个使用正则表达式来解析基本类型和字符串的文本扫描器。Scanner扫描器除上述读入输入流一行功能外,有以下几种用法:

        (1)用于输入流的读入: 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配。然后可以使用不同的 next 方法将得到的标记转换为不同类型的值。

            int test;
            Scanner sc = new Scanner(System.in);
            test = sc.nextInt();
            System.out.println("have entered a int:" + test);
            double test1;
            Scanner sc1 = new Scanner(System.in);
            test1 = sc1.nextDouble();
            System.out.println("have entered a double:" + test1);

        (2)用于扫描字符串或文件,利用分隔符做处理。默认使用空格做分隔符,但也可以重定义分隔符。注释行表示使用空格、逗号或点号做分隔符。

        Scanner s = new Scanner("123 asdf sd 45 789 sdf asdfl,sdf.sdfl,asdf    ......asdfkl    las"); 
        //s.useDelimiter(" |,|\."); 
        while (s.hasNext()) { 
            System.out.println(s.next()); 
        }        

        (3)逐行扫描文件并逐行输出

            public static void main(String[] args) throws FileNotFoundException { 
                    InputStream in = new FileInputStream(new File("C:\AutoSubmit.java")); 
                    Scanner s = new Scanner(in); 
                    while(s.hasNextLine()){ 
                            System.out.println(s.nextLine()); 
                    } 
            }
  • 相关阅读:
    7.31实习报告
    7.30实习报告
    7.29实习报告
    7.28实习报告
    7.27实习报告
    2019-2020-1学期 20192418《网络空间安全专业导论》第八周学习总结
    2019-2020-1学期 20192418 《网络空间安全专业导论》第七周学习总结
    2019-2020-1学期 张曦 白胤廷 邢继元 宗俊豪小组《网络空间安全专业导论》小组讨论议题及脑图
    2019-2020-1学期 20192418《网络空间安全专业导论》第六周学习总结
    2019-2020-1学期 20192418 《网络空间安全专业导论》第五周学习总结
  • 原文地址:https://www.cnblogs.com/north-north/p/3770520.html
Copyright © 2011-2022 走看看