Java读取文档分类赋权值&末行缺失处理"以分类赋权实验为例"

Java读取文档分类赋权值&末行缺失处理

import java.io.*;  
import java.util.Scanner;
public class Q10 {

	public static void main(String[] args) 
			throws FileNotFoundException {
		// TODO Auto-generated method stub
		Scanner input = new Scanner (new File("/Users/apple/Documents/Class Folders/Java/Lab6/Q10.txt"));//读取文件
		int times = 1;
		int miles = 0;
		String kind ="x";
		int sum = 0;
		while(input.hasNextLine()) {
			String line = input.nextLine();
			
				Scanner lineScan = new Scanner (line);
				if(lineScan.hasNextInt()) {
				//这里是读取第一位为整数的情况
					miles = lineScan.nextInt();
					if (kind.equals("firstclass")) {
					//kind已在上一行的读取中赋值
						times = 2;
					}else if(kind.equals("coach")) {
						times=1;
					}else {
						times=0;
					}
					sum=sum+times*miles;
				}
				while(lineScan.hasNext()) {
					kind = lineScan.next();
					if(lineScan.hasNextInt()) {
					//仅输入后一位有整数的情况,避免末行数字无法读取
						miles = lineScan.nextInt();
						if (kind.equals("firstclass")) {
							times = 2;
						}else if(kind.equals("coach")) {
							times=1;
						}else {
							times=0;
						}
						sum=sum+times*miles;
					}
					
					
			}
				
		}
	System.out.println(sum);//打印结果
	
	}

}

你可能感兴趣的:(Java)