在数组中交换两个字符串,Java

时间:2014-02-19 05:44:53

标签: java arrays

我遇到了在我的数组中交换两个字符串的问题。假设Array [0]是“Daniel”而Array [1]是“Paul”,你怎么去切换它们?

这是我的代码,它只会给我带来一堆错误。

public void swap()
{
    String name1;
    String name2;
    String temp1;
    String temp2;
    System.out.print("\nWhich person would you like to swap?: ");
    name1 = input.next();
    System.out.print("Who are they swapping with?: ");
    name2 = input.next();

    for (int i = 0; i <= 10; i++)
    {
        if(seats[i] == name1)
        {
            temp1 = name1;
            temp2 = name2;
            name1 = temp2;
            name2 = temp1;  
            return;
        }
    }

    System.out.println(name1 + " and " + name2 + " have been swapped.\n");
}

非常感谢任何帮助,提前谢谢。

2 个答案:

答案 0 :(得分:1)

==测试参考相等性。

.equals()测试价值平等。

temp1 = name1;
name1 = name2;
name2 = temp1;

应该这样做。 假设您已使用至少10个字符串初始化string[] seats = {"Paul","Sam"};

Scanner input = new Scanner(System.in);

答案 1 :(得分:0)

if(seats[i] == name1) //这是错误的

比较字符串时,您应该使用.equals.EqualsIgnoreCase

if(seats[i].equals(name1){
        temp1 = name1;
        temp2 = name2;
        name1 = temp2;
        name2 = temp1;  

//you can directly do this to swap
  //  temp = name1;
  //  name1 = name2;
  //  name2 = temp;

}