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

版权声明:转载请注明出处 https://blog.csdn.net/Rex_WUST/article/details/88572001

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

package com.wangcong.test;

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 每次读取一行数据

package com.wangcong.test;

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 每次读取一个数据

package com.wangcong.test;

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 读取用空格分隔开的数字字符串,然后将其存入数组(刷题时常用)

基础的实现方式:

package com.wangcong.test;

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();

	}
}

兼容性更强的实现方式 :

package com.wangcong.test;

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

扫描二维码关注公众号,回复: 5564403 查看本文章

猜你喜欢

转载自blog.csdn.net/Rex_WUST/article/details/88572001
sc"
sc
今日推荐