首页 > 解决方案 > 如何输入不同类型的数据并根据它们输出文本?

问题描述

我有一个这样的输入文件:

add_student John 18 180 2014

其中John是名字,18是年龄,180是身高,2014是入学年份。

如何从输入文件中获取这些值,并在单独的输出文件中输出类似的内容,例如:

Student's name: John
Student's Age: 18
Student's Year of Admission: 2014

标签: java

解决方案


查看此代码。我试图添加一些评论。希望这对你来说很清楚。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Program {

    public static void main(String[]args){

        try {
        // Read the txt file
        Scanner scanner = new Scanner(new  File("data.txt"));
        // Loop through all the lines in the file
        while(scanner.hasNextLine()){
            // Store the line
            String line = scanner.nextLine();
            // Split the line by (spaces)
            String[] studentInfo = line.split(" "); // This will produce the following array {"add_student","john",18,180,2014}
            // Print the data
            System.out.println("Student's name : " + studentInfo[1]);
            System.out.println("Student's age : " + studentInfo[2]);
            System.out.println("Student's height : " + studentInfo[3]);
            System.out.println("Student's year of admission : " + studentInfo[4]);
            }

    }catch(FileNotFoundException e){
        // Do whatever you want in case the file not found
        e.printStackTrace();
        }

        }

    }

推荐阅读