我目前正在学习如何在 Java 中使用数组列表,但我遇到了一个简单但烦人的问题..
import java.util.*;
public class ReplacingALetter
{
public static void main (String[] args)
{
String word = "Banana";
List underscore = new ArrayList(word.length());
int i;
for (i=0; i<word.length(); i++)
{
underscore.add(i, "x");
}
System.out.print(underscore);
System.out.println();
System.out.print("Enter a letter: ");
Scanner sc = new Scanner(System.in);
String letter = sc.nextLine();
if (sc.equals("B"))
{
underscore.set(word.indexOf("B"),"B");
}
System.out.print(underscore);
}
}
出于某种原因,它没有用字母 B 替换数组“下划线”中的第一个 x:/
该代码的输出是 [ xxxxxx ]
但是当我输入这段代码时:
import java.util.*;
public class ReplacingALetter
{
public static void main (String[] args)
{
String word = "Banana";
List underscore = new ArrayList(word.length());
int i;
for (i=0; i<word.length(); i++)
{
underscore.add(i, "x");
}
System.out.print(underscore);
System.out.println();
System.out.println("Switching First x with B: ");
underscore.set(word.indexOf("B"),"B");
System.out.print(underscore);
}
}
它工作得很好,输出是 [ B xxxxx ]
无法弄清楚我做错了什么......