java - Objects not staying in ArrayList -


i writing program supposed allow user enter course school. however, couple problems.

  • first, can't reason take more 1 word coursetitle. if 2 words entered, throws error.
  • second, it's not "permanently" adding these classes arraylist?

here's how it's supposed work:

please select following options:

  1. add course
  2. add student course
  3. view available courses
  4. exit system

this isn't being stored file, i'm not sure how keep courses in memory. anyway, here's i've got.

    if(userchoice==1)     {         system.out.println("enter course number: ");         int coursenum=scan.nextint();         system.out.println("enter course title: ");         string coursetitle=scan.next();         system.out.println("enter max number allowed students: ");         int coursemaxsize = scan.nextint();         system.out.println("course number "+coursenum);         system.out.println("course title "+coursetitle);         system.out.println("max number of students "+coursemaxsize);         schoolclass nc = new schoolclass(coursenum,coursetitle,coursemaxsize);         arraylist<schoolclass> coursearr=new arraylist<schoolclass>();         coursearr.add(nc);         system.out.println(coursearr.get(0).getcoursetitle()+" "+coursearr.get(0).getcoursenumber()+" "+coursearr.get(0).getmaxstudents());         system.out.println(coursearr.size()); 

my schoolclass class looks this:

int coursenumber,maxpeers; string course=""; public schoolclass(int coursenum, string coursetitle, int maxstudents) {     coursenumber=coursenum;     course=coursetitle;     maxpeers=maxstudents; } public int getcoursenumber() {     return coursenumber; } public int getmaxstudents() {     return maxpeers; } public string getcoursetitle() {     return course; } 

i have yet write code options 2, 3, 4 obviously. looking little keep me going.

first, can't reason take more 1 word coursetitle.

it because code does:

    system.out.println("enter course title: ");     string coursetitle = scan.next(); 

it should scan.nextline(). documentation scanner says that:

a scanner breaks input tokens using delimiter pattern, default matches whitespace.

and .next() grabs 1 token.

second, it's not "permanently" adding these classes arraylist?

it because list created within if branch:

if (userchoice == 1) {     // ....     arraylist<schoolclass> coursearr = new arraylist<schoolclass>();     coursearr.add(nc);     // ... } // "coursearr" not exist anymore here 

you have create list out of if branch (and out of enclosing loop well, grabs user choice).


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -