我想要反转给我的清单中的名字(编辑:通过网站废弃网站给我)再次不做作业
小样本清单:
Baynes,Aron肯兹郡巴泽莫尔比尔,布拉德利…
如果您在文件中包含所有名称(例如 names.txt ):
names.txt
Baynes, Aron Bazemore, Kent Beal, Bradley Beasley, Malik Beasley, Michael Belinelli, Marco Bell, Jordan Bembry, DeAndre'
您可以:
import java.io.BufferedReader; import java.io.FileReader; public class Main { public static void main(String[] args) { // File name String fileName = "names.txt"; String separator = ", "; String line; try (FileReader fileReader = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(fileReader)) { while ((line = bufferedReader.readLine()) != null) { String[] elements = line.split(separator); if (elements.length == 2) { System.out.printf("%s %s\n", elements[1], elements[0]); } else { System.out.println("Wrong line: " + line); } } } catch (Exception e) { e.printStackTrace(); } } }
或使用 List 而不是文件:
List
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList( "Baynes, Aron", "Bazemore, Kent", "Beal, Bradley", "Beasley, Malik", "Beasley, Michael", "Belinelli, Marco", "Bell, Jordan", "Bembry, DeAndre'" )); String separator = ", "; // Using loop for (String person : list) { String[] elements = person.split(separator); if (elements.length == 2) { System.out.printf("%s %s\n", elements[1], elements[0]); } else { System.out.println("Wrong line: " + person); } } // Using stream list.forEach(person -> { String[] elements = person.split(separator); if (elements.length == 2) { System.out.printf("%s %s\n", elements[1], elements[0]); } else { System.out.println("Wrong line: " + person); } }); } }