Java read the document classification empowering the last line missing values & process "to empower the classification experiments, for example."

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Hollen0318/article/details/102753399

Reads the document classification empowerment experiment

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);//打印结果
	
	}

}

Guess you like

Origin blog.csdn.net/Hollen0318/article/details/102753399