0

I'm having a problem swapping two strings in my array. Let's say Array[0] is "Daniel" and Array[1] is "Paul", how do you go about switching them?

This is my code and it just throws a bunch of errors at me.

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");
}

Any help would be greatly appreciated, thanks in advance.

startrak209
  • 7
  • 1
  • 3

2 Answers2

1

== tests for reference equality.

.equals() tests for value equality.

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

should do it. assuming u have initialised string[] seats = {"Paul","Sam"}; with atleast 10 strings

and

Scanner input = new Scanner(System.in);
sr01853
  • 6,043
  • 1
  • 19
  • 39
  • I think that works, but now when I try to print out the array it's giving me a "NullPointerException." When I want to print out the array, I want it to display the position in the array, then the name. And if a slot in the array is null, don't print anything. But it just gives me that exception error. – startrak209 Feb 19 '14 at 05:58
0

if(seats[i] == name1)// this is wrong

when you compare Strings you should use .equals or .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;

}
Ashish
  • 1,943
  • 2
  • 14
  • 17