使用for循环为char数组赋值后,如何在for循环外访问这些值?因为我需要稍后操作值,删除重复的值。感谢您的任何帮助。非常感激。
public static void processLine(File input, File output) throws FileNotFoundException{
Scanner i = new Scanner(input);
PrintStream o = new PrintStream(output);
while(i.hasNextLine()){
String text = i.nextLine();
char[] pos = new char[text.length()];
for (int x = 0; x < text.length();x++){
pos[x] = text.charAt(x);
}
}
}
答案 0 :(得分:1)
如前所述user3580294,只需通过声明执行循环的结构来存储数据。然后在循环内部存储数据,在循环之后,您可以享受它并使用它!
public static void processLine(File input, File output) throws FileNotFoundException{
Scanner i = new Scanner(input);
PrintStream o = new PrintStream(output);
ArrayList<String> saved= new ArrayList<String>();
while(i.hasNextLine()){
String text = i.nextLine();
char[] pos = new char[text.length()];
for (int x = 0; x < text.length();x++){
pos[x] = text.charAt(x);
}
saved.add(text);
}
// you can use "saved" here ! :) but this code can be shorter I think
}
您可以删除此步骤:
for (int x = 0; x < text.length();x++){
pos[x] = text.charAt(x);
并将其替换为:
saved.add(text);
最终结果应为:
public static void processLine(File input, File output) throws FileNotFoundException{
Scanner i = new Scanner(input);
PrintStream o = new PrintStream(output);
ArrayList<String> saved= new ArrayList<String>();
while(i.hasNextLine()){
String text = i.nextLine();
saved.add(text);
}
// you can use "saved" here ! :) enjoy
}