public void setModel(String model) {_model = model;} // private variable has _ other is supplied make
public void setMake (String make) {_make = make; }
public void setYear (int year) //{_year = year; }
// year can't be less than 1900 or more than 2015
{
while(year < 1900 || year > 2015)
{
System.out.println("Please enter valid year");
year = scan.nextInt();
}
_year = year;
This code works, but if I allow {_year = year} to run in my
'year' setter it won't recognise the variable 'year' in my while loop..
Can somebody explain to me in simple terms why this is the case?
also, if there is a better way to format a question for legibility's sake please let me know ;)
I'm not understanding what you mean. The { and } would open and close your setter, so the setter would only be to set _year to the value of year.
If you do this:
private int _year; public void setYear (int year) { _year = year; }The only _year is set. This is the scope of the 'year' variable. Only available in setYear.
If that while loop is supposed to be inside the setYear setter, that's a different story. It would be weird to have validation inside a setter that necessitates input from the console, though. I would think you'd want something more like this:
// main.java import java.util.Scanner; public class main { public static void main(String[] args) { Car car = new Car(); Scanner scan = new Scanner(System.in); System.out.println("Enter the make"); String make = scan.nextLine(); System.out.println("Enter the model"); String model = scan.nextLine(); int year = 0; do { System.out.println("Enter the year"); year = scan.nextInt(); } while (year < 1900 || year > 2015); car.setMake(make); car.setModel(model); car.setYear(year); System.out.println(car.getYear() + " " + car.getMake() + " " + car.getModel()); } }// Car.java public class Car { private String _model; private String _make; private int _year; public void setModel(String model) { _model = model; } public void setMake (String make) { _make = make; } public void setYear (int year) { _year = year; } public String getModel() { return _model; } public String getMake() { return _make; } public int getYear() { return _year; } }