1
public Student(String name, String sch, int stay, String year)
{
    String name1 = getInput("Enter your name:");
    this.name = name1;  
    String sch1 = getInput("Enter your scholarship:");
    this.sch = sch1;    
    String number = getInput("Enter years of stay: ");
    this.stay = Integer.parseInt(number);

    for (int i=0; i < programList.size(); i++)
    {
        if (stay==1)
        {
        //If the student's year of stay is only 1 year I will  put he/she to the "freshmenList". How will I do that?
        }

    }

Here's my code. I want to sort the inputed elements to a new ArrayList according to the years of stay input. (If year of stay = 1 then freshmen arraylist, if=2 then sophomore arraylist, so on). How will I do that? Thank you!

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
James
  • 29
  • 5
  • `freshmenList.add(this);` And I'm pretty sure that you don't want to have this `for` loop in the `Student` constructor. – Tom Feb 13 '16 at 13:33
  • So I will disregard the for loop here then it will only be: if (stay==1) freshmenList.add(this.name) ? – James Feb 13 '16 at 13:37
  • If you only want the name, then yes. – Tom Feb 13 '16 at 13:39
  • I tried the code but it says: The method add(Student) in the type ArrayList is not applicable for the arguments (String) – James Feb 13 '16 at 13:44
  • `add(new Student(your params))` since type `ArrayList`. – SatyaTNV Feb 13 '16 at 13:46
  • Because you obviously don't just want the name :P. Use the code from my first comment (if that code is still in the constructor. You just don't need to wrap the `if (stay==1)` with your `for` loop). – Tom Feb 13 '16 at 13:48
  • 1
    Ok got it! Thank you Tom and Satya :D – James Feb 13 '16 at 14:16
  • Getting user input from the constructor sounds like a really bad idea... I wish I could tell you exactly why http://stackoverflow.com/questions/7048515/is-doing-a-lot-in-constructors-bad – Ruan Mendes Feb 13 '16 at 15:53

1 Answers1

0

I recommend that you would use a switch for this, they are a bit better readable (imo) and are supposed to be faster than a bunch of if statements:

switch (stay)
{
    case 1:
        freshmenList.add(this);
        break;

    case 2:
        sophomoreList.add(this);
        break;

    ...
    default:
        //Do something with invalid answers
}
S.Klumpers
  • 410
  • 3
  • 14