java - Custom Object Arrays and For Loops -
i'm trying make program has array of person objects called "personarray" populated loop reads user input 3 separate variables , turns variables person object , adds array.
here code person.java:
public class person { private string firstname, lastname; private int zip; public person(string fname, string lname, int perzip) { firstname = fname; lastname = lname; zip = perzip; } }
and here code persondriver.java:
import java.util.scanner; public class persondriver { public static void main(string[] args) { scanner scan = new scanner(system.in); string firstname, lastname; int zipcode; person[] personarray = new person[25]; (int = 0; < 25; i++) { system.out.println("enter first name: "); firstname = scan.nextline(); system.out.println("enter last name: "); lastname = scan.nextline(); system.out.println("enter zip: "); zipcode = scan.nextint(); personarray[i] = new person(firstname, lastname, zipcode); } scan.close(); system.out.println(personarray); } }
funny story: frustrating , common error came across when java newbie.
put scan.nextline()
after zipcode. not save value. call method.
the reasoning behind when call nextint()
, scanner's cursor moves position after integer, not next line if newline follows integer. when call nextline()
, grabs characters between cursor , next newline character comes across, in case blank string. example, if have input such as:
alec
parsons
60120
the first iteration work fine, cursor stay on zip code's line, so:
alec
parsons
60120i
at next call nextline()
firstname, instead receive blank string. eventually, program call nextint()
on string value, throw exception.
it's not intuitive, that's how scanner works.
edit: also, pointed out in comments, every java object has string representation, putting array inside println()
syntactically correct. however, string representation not readable. want loop through each person , print his/her information. 1 awesome thing java can define how class represented string overriding tostring()
method. put method in person class:
public string tostring() { // can define how person represented in string form here return "name: " + firstname + " " + lastname + "\n" + "zip: " + zip; }
this way, can use person argument println()
, , java automatically print out information in desired format.
for(person p: personarray) system.out.println(p);
name: alec parsons
zip: 60120
Comments
Post a Comment