Java 如何输入不同类型的数据并基于它们输出文本?
我有一个输入文件,其中的行如下:Java 如何输入不同类型的数据并基于它们输出文本?,java,Java,我有一个输入文件,其中的行如下: add_student John 18 180 2014 其中约翰是名字,18岁是年龄,180岁是身高,2014年是入学年份 如何从输入文件中获取这些值,并在单独的输出文件中输出类似的内容,例如: Student's name: John Student's Age: 18 Student's Year of Admission: 2014 查看此代码。我试图添加一些评论。希望你能明白 import java.io.File; import java.io.
add_student John 18 180 2014
其中约翰是名字,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();
}
}
}
查看此代码。我试图添加一些评论。希望你能明白
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();
}
}
}
读取文件,使用
split()
方法拆分字符串。就这些。我是个初学者,对我来说没那么简单。到目前为止你都做了些什么?添加代码。读取文件,使用split()
方法拆分字符串。就这些。我是个初学者,对我来说没那么简单。到目前为止你都做了些什么?添加您的代码。