0

I want to have an array of strings and two methods,one gets some (10 for example)strings and save them in order and the second method gets one of those strings and returns the array index where it is saved.But my code just save the the first string.Can you help?

public void savingselectedcourses(String coursenum){
    for( n=0;n<=9;n++){
        sc=selectedcourses[n];
        if(sc==null)
            selectedcourses[n]=coursenum;
        chta.setText(sc);
    }
}

public int removingcourses(String coursenum){
    for( m=0;m<=9;m++){
        if(selectedcourses[m]==coursenum)
            break;
    }
    return m;
}

Thanks for you responses.

Ishnark
  • 661
  • 6
  • 14
Rasoul.A
  • 1
  • 1
  • 2
    There is no string array in your code. – Christopher Schneider Jun 23 '17 at 15:32
  • 2
    This code doesn't look like it compiles, have you tested this? What is the current output(s)? – ZeldaZach Jun 23 '17 at 15:33
  • Can you please specify what is exact issue in your code – gati sahu Jun 23 '17 at 15:34
  • you are just passing one string to your method and saving that single string on all the indexes in array in savingselectedcourses method. If you want different strings to be stored, you need to pass 10 different strings to your method using an array or list etc – digidude Jun 23 '17 at 15:34
  • Unclear what you are asking. However, to sort you can use [`Arrays.sort()`](https://stackoverflow.com/questions/12986386/why-does-my-sorting-loop-seem-to-append-an-element-where-it-shouldnt) – Blasanka Jun 23 '17 at 15:35
  • Welcome to StackOverflow, please review the guide on posting code samples: https://stackoverflow.com/help/mcve. Notably the code should be complete (sc, chta and selectedcourses variables are not posted), and you should provide a sample of what is currently happening and what you want to happen. – Jamey Jun 23 '17 at 15:36

2 Answers2

0

Why are you trying to reinvent the wheel? Use an ArrayList instead as this can give you the index of an element in the list:

List<String> list = new ArrayList<>();

// add elements
list.add("first");
list.add("second");

// get index of an element
list.indexOf("second");
grthr
  • 86
  • 6
0

Your code is not clear to be honest but hope this method below helps

    public static int test(String s){
    for(int counter=0; counter< names.length;counter++){
        if(names[counter].compareTo(s)==0){
            return counter;
        }

    }
    return -1;
}

it accepts a string and compare it with all the string in array if it matches it returns the index otherwise it returns -1

array has to be defined in class not inside the method if you want to use my method