I have an array contains 15 full names, how do I break it into 2 arrays(first and last name) below is the method for my full name array
public static void readData(String file) throws FileNotFoundException {
x = new Scanner(new File(file));
//count number of names in the array
int n = 0;
while(x.hasNextLine()) {
n++;
x.nextLine();
}
//open another scanner to avoid null
Scanner x1 = new Scanner(new File(file));
name = new String[n];
//get the array and print
for(int i = 0; i < name.length; i++ )
name[i] = x1.nextLine();
System.out.println(Arrays.toString(name));
}
File contains 15 full names like this:
Max Frei
Stephen King
Agatha Christie
How to read:
final int total = 15;
String[] firstNames = new String[total];
String[] lastNames = new String[total];
try (Scanner scan = new Scanner(new File("file"))) {
for (int i = 0; i < total; i++) {
firstNames[i] = scan.next();
lastNames[i] = scan.next();
}
}
// firstNames: Max, Stephen, Agatha
// lastNames: Frei, King, Christie
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.