Java如何读取数据,直到文件尾——while (sc.hasNext())

 1 输入空格隔开的数字,然后求和

import java.util.Scanner;

public class Test1 {
	 public static void main(String[] args) {
	        Scanner scan = new Scanner(System.in);
	 
	        double sum = 0;
	        int m = 0;
	 
	        while (scan.hasNextDouble()) {
	            double x = scan.nextDouble();
	            m = m + 1;
	            sum = sum + x;
	        }
	 
	        System.out.println(m + "个数的和为" + sum);
	        System.out.println(m + "个数的平均值是" + (sum / m));
	        scan.close();
	    }
}

运行结果:

1 2 3
3个数的和为6.0
3个数的平均值是2.0
 

 注意当在键盘输入Ctrl+Z之后,程序才停止读入,开始执行求和。


2 每次读取一行数据

import java.util.Scanner;

public class Test2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		//是否还有下一行
		while (sc.hasNextLine()) {
			String str = sc.nextLine();//读取一行,保留空格
			System.out.println("输出:"+str);
		}
		
		sc.close();
	}
}

运行结果: 

123 456 789
输出:123 456 789
111   111   111
输出:111   111   111


3 每次读取一个数据

import java.util.Scanner;

public class Test2 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		//是否还有下一个元素
		while (sc.hasNext()) {
			String str = sc.next();//读取一个元素,不保留空格
			System.out.println("输出:"+str);
		}
		
		sc.close();
	}
}

运行结果:

123 456 798
输出:123
输出:456
输出:798
111   111   111
输出:111
输出:111
输出:111

想退出循环可以参考https://mp.csdn.net/postedit/88424076 


4 读取用空格分隔开的数字字符串,然后将其存入数组(刷题时常用)

基础的实现方式:

import java.util.Scanner;

public class Test {
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);

		while (sc.hasNextLine()) {
		
			String[] str = sc.nextLine().split(" ");
			int[] num = new int[str.length];

			for (int i = 0; i < str.length; i++)
				num[i] = Integer.parseInt(str[i]);// 将字符串的数字保存到整型数组里

			for (int i = 0; i < num.length; i++)
				System.out.println("输出:"+num[i]);

		}

		sc.close();

	}
}

兼容性更强的实现方式 :

import java.util.Scanner;

public class Test {
	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);

		while (sc.hasNextLine()) {
			// String.trim()可以删除字符串首尾的空格。
			// String.split("\\s+") //用正则表达式匹配多个空格,即使遇到多个空格也能分隔
			String[] str = sc.nextLine().trim().split("\\s+");
			for(String s:str) {
				System.out.println(s);
			}
			int[] num = new int[str.length];

			for (int i = 0; i < str.length; i++)
				num[i] = Integer.parseInt(str[i]);// 将字符串的数字保存到整型数组里

			for (int i = 0; i < num.length; i++)
				System.out.println("输出:"+num[i]);

		}

		sc.close();

	}
}

123 456
123
456
输出:123
输出:456
   123   456
123
456
输出:123
输出:456


 

笔试常用:提取"[22,33,55]"中的数字,然后将这些数字存入数组。

        String str = "[22,33,55]";
        String strTmp=str.substring(1,str.length()-1);//取子串,从而去除掉头尾的"["和"]",从而strTmp="22,33,55"
        String[] strArray = strTmp.split(",");//按“,”切分字符串
        int [] numArray=new int[strArray.length];
        /* 将字符串数组 转换成 int数组 */
        for (int i = 0; i < strArray.length; i++) {
            numArray[i]=Integer.parseInt(strArray[i]);
        }

        /* 测试结果 */
        for (int i = 0; i < numArray.length; i++) {
            System.out.println(numArray[i]);
        }

 

利用正则表达式,从字符串中取出所有数字

        /* 取出字符串中所有数字 */
        String s1 = "a9fil3dj11P0jAsf11j";
        String[] exprs = s1.split("\\D+"); //非数字字符匹配。等效于 [^0-9]。
        for (int i = 0; i < exprs.length; i++) {
            System.out.println(exprs[i]);
        }

 执行结果:


9
3
11
0
11

注意:9上面有一行空格。


 

 

利用正则表达式,从字符串中取出所有英文字母

        /* 取出字符串中所有的字母 */
        String s2 = "a9fil3dj11P0jAsf11j";
        String[] exprs2 = s2.split("[^A-Za-z]");
        for (int i = 0; i < exprs2.length; i++) {
            System.out.println(exprs2[i]);
        }
        // \w  匹配任何字类字符,包括下划线。与"[A-Za-z0-9_]"等效。
        // \W  与任何非单词字符匹配。与"[^A-Za-z0-9_]"等效。

执行结果:

a
fil
dj

P
jAsf

j

注意:中间有几个空格


跳出循环的方法

import java.util.Scanner;
 
public class ScannerKeyBoardTest1 {
 
	public static void main(String[] args) {
 
		// 例:当输入"0"时,循环结束
		Scanner sc = new Scanner(System.in);
		while (!sc.hasNext("0")) {
			System.out.println("键盘输入的内容是:"+sc.next());
		}
	}
}

 

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值