我目前正在学习如何在 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 :/
该代码的输出是 [ x x x x x x ]
但是当我输入此代码时:
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 x x x x x ]
不知道我做错了什么......
最佳答案
我在您的两个示例中发现的唯一区别是,其中一个使用了 if 条件:
if (sc.equals("B")) {
underscore.set(word.indexOf("B"),"B");
}
而另一个执行
underscore.set(word.indexOf("B"),"B");
无条件。您的 sc
是一个 java.util.Scanner
,"B"
是一个字符串。它们不能相等,因此在第一个示例中永远不会调用该方法。
关于java - 程序不替换字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14367376/