如何创建以{<1> name姓氏”形式(例如:Anna Hale)发送名称为array
的方法。该方法(通过返回语句)以“ first --- last”的形式返回名称。以下是我的全名数组
public static void readData(String file) throws FileNotFoundException {
x = new Scanner(new File(file));
n = 0;
while(x.hasNextLine()) {
n++;
x.nextLine();
}
name = new String[n];
Scanner x1 = new Scanner(new File(file));
for(int i = 0; i < name.length; i++ )
name[i] = x1.nextLine();
System.out.println(Arrays.toString(name));
}
答案 0 :(得分:1)
这里是完整的代码,假设您想从file
中读取。请更正您发布的代码中的编译时错误。由于您事先不知道数组的长度,因此无法初始化数组,也可以更改逻辑以获取行数,然后初始化数组。
文件内容如下:
abc xyzzy
And sdff
Asdf sdfw
输出如下所示
[abc--xyzzy, And--sdff, Asdf--sdfw]
在下面的代码中,name[i].replace(" ", "--");
用" "
替换了空间--
代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Post1 {
public static void main(String[] args) throws FileNotFoundException {
String[] transformedNames = readData("/Users/kuma/Desktop/post1.txt");
System.out.println(Arrays.toString(transformedNames));
}
public static String[] readData(String file) throws FileNotFoundException {
Scanner x = new Scanner(new File(file));
List<String> list = new ArrayList<>();
while(x.hasNextLine()) {
list.add(x.nextLine());
}
x.close();
String[] name = new String[list.size()];
list.toArray(name);
String[] transformedNames = new String[list.size()];
for(int i = 0; i < name.length; i++ )
transformedNames[i] = name[i].replace(" ", "--");
return transformedNames;
}
}
在Java 8中,使用stream
API可以实现相同的目的:
private static String[] readDataUsingJava8() {
String[] transformedNames = null;
try (Stream<String> stream = Files.lines(Paths.get( "/Users/kuma/Desktop/post1.txt"))) {
transformedNames =
stream.map(new Function<String, String>() {
@Override
public String apply(String t) {
// TODO Auto-generated method stub
return t.replace(" ", "--");
}
}).toArray(String[]::new);
} catch (IOException e) {
e.printStackTrace();
}
return transformedNames;
}