java - 如何输入不同类型的数据并根据它们输出文本?
问题描述
我有一个这样的输入文件:
add_student John 18 180 2014
其中John是名字,18是年龄,180是身高,2014是入学年份。
如何从输入文件中获取这些值,并在单独的输出文件中输出类似的内容,例如:
Student's name: John
Student's Age: 18
Student's Year of Admission: 2014
解决方案
查看此代码。我试图添加一些评论。希望这对你来说很清楚。
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();
}
}
}
推荐阅读
- sql - SQL 迁移脚本 - 插入到带有输出 ID 的选择中
- c# - 将 dotnet dev-certs 与 aspnet docker 映像一起使用
- python - 如何解决安装构建工具的问题
- javascript - 如何在新的 Reactjs 函数中设置状态?
- docker - 在 DinD 中构建 GitLab 失败并显示“请在提交前提供带有 `from` 的源图像”
- pandas - 如何将序列号设置为空值?
- asp.net - 更新面板不适用于按钮单击,单击 asp.net 中的按钮时会重新加载页面
- python - 在线程中运行子进程并停止它
- java - 无法调用“org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)”,因为“this.searchContext”为空
- regex - 如何使用空手道中的包含将字符串列表与子字符串匹配