Agrim Nautiyal
Agrim Nautiyal

Reputation: 11

Error in swapping characters in stringbuffer object

i am trying to sort a string in the alphabetical order, however i am facing an error in the line :

 sb.charAt(j)=sb.charAt(j+1);

where the compiler shows an error as expected variable; found value

the rest of the code is as follows :

import java.util.Scanner;
class a
{
 public static void main(String[] agrs)
{
    Scanner sc = new Scanner(System.in);
    String s = sc.next();
    StringBuffer sb = new StringBuffer();
    sb.append(s);
    for(int i = 0; i< s.length(); i++)
    {
        for(int j = 0; j<s.length(); j++)
        {
            if(s.charAt(j)>s.charAt(j+1)){
            char temp = s.charAt(j);
            sb.charAt(j)=sb.charAt(j+1);
            sb.charAt(j+1)=temp;
        }
    }
}}}

kindly help me out as i'm a beginner and i cannot figure out why this issue is occurring , thank you .

Upvotes: 1

Views: 215

Answers (4)

Ethan
Ethan

Reputation: 1

This method can only return values and can not set values, I guess you might want to use this method:

setCharAt()

It can meet your requirement

Upvotes: 0

Urvashi Soni
Urvashi Soni

Reputation: 279

As already answered by many, the issue is in charAt(index) you are using, as this returns the character at the given index rather than setting a char at the index position. My answer is to divert your approach of sorting. For simpler solutions, where smaller data sets (like your problem) are used, you should use the predefined sorting algorithms, like Insertion Sort You may get help for the algo from here: http://www.geeksforgeeks.org/insertion-sort/

Upvotes: 1

Ruslan Akhundov
Ruslan Akhundov

Reputation: 2216

StringBuffer's charAt returns just the value of the char at the index, if you want to swap two chars you need to use setter for that, so you possible want to do somtehing like:

for(int j = 0; j < s.length() - 1; j++) {
    if(s.charAt(j) > s.charAt(j + 1)) {
        char temp = s.charAt(j);
        sb.setCharAt(j, sb.charAt(j + 1));
        sb.setCharAt(j + 1, temp);
    }
}

Upvotes: 0

Lothar
Lothar

Reputation: 5449

This looks like a homework assignment where the goal is to sort the characters of a text being entered, so if you enter gfedbca the result should be abcdefg.

You already got a comment telling you what the problem is: StringBuffer#charAt() is not returning a reference to StringBuffer's internal array that you can change the value of. Dependent on the actual assignment you can call StringBuffers setCharAt method or you can go another approach by converting the text to sort to a char array and do the sorting in there. There are actually helper-classes in the JVM, that do that for you, have a look e.g. at the class java.util.Arrays

Upvotes: 1

Related Questions