How to edit instance variable in method and read in different method - java

I'm pretty new to java and could not find a question answering my problem particulary.
I initialized an arraylist as instance variable and in one method I edit this arraylist which also works, but I'm having trouble storing this value in the instance variable and then reading it in a different method because then it appears empty again. I tried using getter and setter but that didn't really work even though I suppose that that is part of the solution...
Here some relevant snippets of my code:
public class CarManager {
ArrayList<Car> carList = new ArrayList<>();
String carId ="";
String driver= "";
int sizeCategory= 0;
Car myCar= new Car (carId,driver,sizeCategory);`
public void addCar () {
CarManager myCarManager= new CarManager();
Car car1 = new Car(carId,driver,sizeCategory);
carId= car1.getCarId(carId);
driver= car1.getDriver (driver);
sizeCategory= car1.getSizeCategory (sizeCategory);
System.out.println("You entered the following data:");
System.out.println("\ncar ID: "+ carId);
System.out.println("driver's name:" +driver);
System.out.println("size category: "+sizeCategory);
System.out.println("\nIf you are okay with this, press 0 to save the data and return to the CARS MENU");
System.out.println("\nIf you made a mistake, press 1 to enter the data again");
Scanner afterAddCar= new Scanner(System.in);
String choice1;
choice1= afterAddCar.next().trim();
if ("1".equals (choice1)) {
myCarManager.addCar();
}
if ("0".equals (choice1)) {
Car returnedCar= new Car (carId,driver,sizeCategory);
carList.add(returnedCar);
String list = carList.toString();
System.out.println(list);
myCarManager.setCarList(carList);
ArrayList<Car> afterAdd= carList;
myCarManager.handleCars();
}
}
public ArrayList<Car> getCarList() {
return carList;
}
public void setCarList(ArrayList<Car> carList) {
this.carList = carList;
}
public void listCars () {
String list = carList.toString();
System.out.println(list);
}
I have a second class called Car which I'll also post here for better understanding:
public class Car {
private String carId;
private String driver;
private int sizeCategory; // value from 1-3 indicating the size of the car
public Car () {}
public Car (String carId,String driver,int sizeCategory){
this.carId= carId;
this.driver= driver;
this.sizeCategory= sizeCategory;
}
public String getCarId(String carId) {
Scanner keyboard = new Scanner(System.in);
System.out.println("\nFirst enter the car ID: " + carId);
while (carId.length() < 6) {
System.out.println("Please enter an ID that has at least 6 characters");
carId = keyboard.next();
}
return carId;
}
public void setCarId(String carId) {
this.carId = carId;
}
public String getDriver(String driver) {
Scanner keyboard = new Scanner(System.in);
System.out.println("\nNext enter the driver's name:" + driver);
driver= driver.trim();
while (driver.length() < 2) {
System.out.println("Please enter a name that has at least 2 characters");
driver = keyboard.next();
driver= driver.trim();
}
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public int getSizeCategory(int sizeCategory) {
Scanner keyboard = new Scanner(System.in);
String input="";
System.out.println("\nNow the size category: ");
while (sizeCategory <1 || sizeCategory >3) {
System.out.println("The size category has to be between one and three");
input = keyboard.next().trim();
try {
sizeCategory = Integer.parseInt(input);
} catch (Exception e) {
sizeCategory = 0;
}
}
return sizeCategory;
}
public void setSizeCategory(int sizeCategory) {
this.sizeCategory = sizeCategory;
}
Now I know that there is probably more than one thing that could be improved here, but I'm mostly interested in solving the problem with the listing of the updated arraylist.
Thanks a lot in advance!

Your problem seems to be that you are creating a new CarManager everytime, and using recursive to go inside a new CarManager that you created in your addCar() method. it looks to me that you only need one CarManager and all the Car instances get added to your ArrayList<Car> that is a field in your Car Manager.
i assumed this because your Car class have fields :
private String carId;
private String driver;
private int sizeCategory;
and the same fields are being repeated in your CarManager for no use basically.
I suggest to use a while loop to check for user input, such as :
public void addCar(Scanner scanner) { // passing on the scanner
while (true) {
// ask the user for inputs
String carId = scanner.nextLine();
String driver = scanner.nextLine();
int sizeCatagory = Integer.parseInt(scanner.nextLine());
// ask user for confirmation
if (scanner.nextLine().equals("1") {
continue;
} else {
carList.add(new Car(carId,driver,sizeCategory));
break;
}
}
}

Related

Can I check the local vairable by using method in other class?

public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu();
}
}
Here's the menu class:
public class BookstoreMenu {
private Scanner sc = new Scanner(System.in);
private BookstoreController bc = new BookstoreController();
public void mainMenu() {
System.out.println("1. SignUp");
System.out.println("2. Check members list");
System.out.println("Select menu : ");
int menu = sc.nextInt();
switch (menu) {
case 1: {
bc.createAccount();
break;
} case 2:
default:
System.out.println("...");
}
}
}
This is controller class where I made methods:
public class BookstoreController {
private Scanner sc = new Scanner(System.in);
public void createAccount() {
System.out.println("Let's get started");
System.out.print("Your name : ");
String[] strArray = new String[0];
String name = sc.nextLine();
strArray = saveId(strArray, name);
System.out.print(name + ", Nice to meet you!");
System.out.println(Arrays.toString(strArray));
}
public String[] saveId(String[] originArr, String name) {
String[] newArr = new String[originArr.length + 1];
System.arraycopy(originArr, 0, newArr, 0, originArr.length);
newArr[originArr.length] = name;
return newArr;
}
}
I'm trying to make a menu with just two options. The first option is Sign Up through createAccount(); and once I finish signing up, I want to go back to the menu class and choose option 2.
I was thinking I could approach the information of strArray in BookstoreController class by typing bc.~ under case 2 of the switch in the BookstoreMenu class, but I failed.
My question is: Is it possible to approach the value which was made in the local area of another class?
No you cannot. Welcome to the world of Object Oriented Programming OOP & design. One of the more important ideas of OOP is that you encapsulate data and then access it through method calls (or, for other languages, properties).
In this case you should return an Account class from createAccount(). Then you can have a method there to the strArray. That variable should be a field in the Account class and be renamed to something that reflects its purpose, rather than the types it is made up of (string and arrays).
Now, in modern Java, we store objects like accounts in lists, not arrays. Lists can be grown at your leisure. I've put the list into a field of the controller, so it can be maintained in the right controlled location.
Here is some example:
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu(new Scanner(System.in), System.out);
}
}
public class BookstoreMenu {
private BookstoreController bc = new BookstoreController();
public void mainMenu(Scanner sc, PrintStream out) {
while (true) {
// this is a "try with resources", using a localized scanner
int menu;
out.println("1. SignUp");
out.println("2. Check members list");
out.println("9. Quit");
out.println("Select menu : ");
menu = sc.nextInt();
// either menu has been assigned, or an exception has been thrown, so we can now use it
switch (menu) {
case 1:
bc.createAccount(sc, out);
break;
case 2:
bc.displayAccounts(out);
break;
// always leave yourself an exit option
case 9:
out.println("Bye");
System.exit(0);
// the default should display an error or warning
default:
out.println("Unknown option, try again");
}
}
}
}
public class BookstoreController {
// the list of accounts that is initially empty, but may grow
private List<Account> accounts = new ArrayList<Account>();
public void createAccount(Scanner sc, PrintStream out) {
out.println("Let's get started");
out.println("Your name : ");
String name = sc.nextLine();
out.println(name + ", nice to meet you!");
Account account = new Account(name);
accounts.add(account);
}
public void displayAccounts(PrintStream out) {
for (Account account : accounts) {
out.println(account);
}
}
}
// this is the additional "data class"
public class Account {
private String name;
// constructor that assigns the name to the field
public Account(String name) {
this.name = name;
}
// a method to retrieve the property name
public String name() {
return name;
}
// this is what is called when it is printed using println (converted to string)
#Override
public String toString() {
return String.format("Account %s", name);
}
}

How can I set variables from a class of ArrayLists to the Main class?

I have already created an object and tried to set some variables but I cannot find the type of the variables that should I create in order to do not have any problem.
The part of the main class:
Menu menu = new Menu();
scanner.nextLine();
System.out.println("Give a code.");
String code = scanner.nextLine();
menu.setCode(code);
System.out.println("Give a main dish");
String MainDish = scanner.nextLine();
menu.setMainDishes(MainDish);
System.out.println("Give a drink.");
String Drink = scanner.nextLine();
menu.setDrinks(Drink);
System.out.println("Give a sweet.");
String Sweet = scanner.nextLine();
menu.setSweets(Sweet);
And the Menu class:
public class Menu {
ArrayList<String> MainDishes = new ArrayList<>();
ArrayList<String> Drinks = new ArrayList<>();
ArrayList<String> Sweets = new ArrayList<>();
private String code;
public ArrayList<String> getMainDishes() {
return MainDishes;
}
public void setMainDishes(ArrayList<String> mainDishes) {
MainDishes = mainDishes;
}
public ArrayList<String> getDrinks() {
return Drinks;
}
public void setDrinks(ArrayList<String> drinks) {
Drinks = drinks;
}
public ArrayList<String> getSweets() {
return Sweets;
}
public void setSweets(ArrayList<String> sweets) {
Sweets = sweets;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
Compliler give an error because of the String variables that I created.
Your menu class contains ArrayList variables and you try to assign a String to them. Instead of:
menu.setMainDishes(MainDish);
Try:
menu.getMainDishes().add(MainDish);
Also, common convention in Java is to start variables with lowercase, eg mainDish.
You are trying to pass a string when the methods are expecting an ArrayList of strings. If you want to do it the way you currently are, then create an ArrayList, put the user input into it, then pass that ArrayList to the methods that call for it.

Java Coding--Inheritance Issues

I am new to java and am having a lot of issues making a multilevel inheritance program.
I'm trying to make a program where my main class (AU) is broken down into subclasses depending on what the user types.
My issue is when I try to call my second level (Part_Time_Student) subclass from my first level subclass (Student).
Whenever I try to call it, it just recalls the first level subclass(the one I'm currently in).
I noticed that if I make my second level subclass(Part_Time_Student) extend the main superclass(AU) it works, but I would prefer to make it extend student.
I realize this is a very complicated post (especially since I don't know the terminology), but I hope my code is easy enough to follow.
AU.java
public class AU {
Scanner input;
static String name;
static Long numb;
public AU() {
}
public void Name() {
input=new Scanner(System.in);
System.out.println("What is the member's name");
String nam = input.nextLine();
AU.name=nam;
System.out.println(nam +" has been added");
}
public void Phone() {
input=new Scanner(System.in);
System.out.println("What is the member's phone number");
Long number = input.nextLong();
AU.numb=number;
System.out.println(number+ " has been saved");
}
}
Main.java
public class Main {
private static Scanner input;
public static void main(String[] args) {
AU au = new AU();
au.Name();
au.Phone();
while (3==3) {
System.out.println("What is your role at the University?");
input=new Scanner(System.in);
String determ=input.nextLine();
if (determ.toUpperCase().equals("STUDENT")) {
Student student=new Student();
break;
}
else if (determ.toUpperCase().equals("STAFF")) {
break;
}
else if (determ.toUpperCase().equals("FACULTY")) {
break;
}
else if (determ.toUpperCase().equals("TESTER")) {
break;
}
else {
System.out.println("Invalid Response");
}
}
System.out.println("yay");
}}
Part_Time_Student.java
public class Part_Time_Student extends Student {
public Part_Time_Student() {
System.out.println("it switched");
System.out.println(GPA);
System.out.println(Assign);
System.out.println(name);
}
public void tester() {
System.out.println("test");
}
}
Student.java
public class Student extends AU {
static double GPA=5;
static String Assign;
public Student() {
super();
System.out.println(name);
System.out.println("Are you a full-time student or part- student(type part or full)");
input=new Scanner(System.in);
while (3==3) {
String get=input.nextLine();
switch (get.toUpperCase())
{
case "PART":{
Student.Assign="Part";
Part_Time_Student Studentp = new Part_Time_Student();
break;
}
case "FULL":{
Student.Assign="Full";
break;
}
default :{
System.out.println("Invalid ");
}}}
}
public void gpa(String grade,long credits) {
System.out.println(name+numb);
name=name;
}
public void Welcome() {
System.out.println("Welcome Student");
}
}
Output:
What is the member's name
-Test
Test has been added
What is the member's phone number
-540
540 has been saved
What is your role at the University?
-student
Test
Are you a full-time student or part-student(type part or full)
-part
Test
Are you a full-time student or part-student(type part or full)
As you can see the command "Part_Time_Student Studentp = new Part_Time_Student();" is just recalling the student class over an over.
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Move your statement Part_Time_Student Studentp = new Part_Time_Student(); out of while loop, infact out of the constructor.
When you are constructing your Student class, and inside when you invoke a constructor of subclass, it in turn calls its super class which is Student, so it goes over and over. So it will keep asking you same question again and again.
Remove the Part_Time_Student constructor from :
case "PART":{
Student.Assign="Part";
// Part_Time_Student Studentp = new Part_Time_Student(); //remove this
break;
}
Change this if condition in your Main class below to:
if (determ.toUpperCase().equals("STUDENT"))
{
Student student=new Student();
if ( student.Assign.equalsIgnoreCase( "Part" ) )
{
Part_time_Student part_time_student = new Part_time_Student();
}
break;
}

Issues using String data type in my constructor, application file not running properly

So i've been messing around with String data types in the constructor of my class file, and while everything compiles correctly, when I run the application file, the program doesn't give the desired result. I kept it short to see if it would work, so my class file is as follows:
public class StringPractice
{
private String color;
private String brand;
public StringPractice() {
String color = "";
String brand = "";
}
public StringPractice(String clor, String brnd) {
setColor(clor);
setBrand(brnd);
}
public void setColor(String clor) {
if (clor.equalsIgnoreCase("Red")) {
color = clor;
}
else {
System.out.println("We dont't carry that color");
}
}
public void setBrand(String brnd) {
if (brnd.equalsIgnoreCase("Gibson")) {
brand = brnd;
}
else {
System.out.println("We do not carry that brand");
}
}
public String getColor() {
return color;
}
public String getBrand() {
return brand;
}
public void display() {
System.out.println("Our brands are: " + brand + "Our colors are: " + color);
}
My application file is as follows:
import java.util.Scanner;
public class UseStringPractice
{
public static void main(String[] args)
{
String brand = "";
String color = "";
Scanner keyboard = new Scanner(System.in);
StringPractice Guitar1;
System.out.println("Please enter the brand you would like");
brand = keyboard.next();
System.out.println("Please enter the color you would like");
color = keyboard.next();
Guitar1 = new StringPractice(brand, color);
Guitar1.display();
}
}
What am I doing incorrectly? Am I using the wrong methods to parse the information from scanner? Or am I using equalsIgnoreCase incorrectly? This is my first attempt at implementing these methods, so I may be wayyy off for all I know. When I run the application class, my result is that of the trailing else clause, or, "We do not carry those brands" or "We don't carry that color". Then, in my display statement, the variable names are replaced with "null". This is all for practice so any insight would be fantastic. Thanks!
Your arguments being passed to your constructor should be flipped.
In your application:
Guitar1 = new StringPractice(brand, color);
but in your code:
public StringPractice(String clor, String brnd) {

Instantiating and Updating Several Objects

Currently I am teaching myself Java but I came across a simple problem but have no one to ask from. From one of the exercises, I wrote a class and write a driver class that instantiates and updates several objects. I am confused by "instantiates and updates several objects." Here is what I mean: So here is my class:
public class PP43Car {
private String make = "";
private String model = "";
private int year;
public PP43Car(String ma, String m, int y)
{
make = ma;
model = m;
year = y;
}
public void setMake(String ma)
{
make = ma;
}
public String getMake()
{
return make;
}
public void setModel(String m)
{
model = m;
}
public String getModel()
{
return model;
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
public String toString()
{
String result = "Make of the vehicle: " + make +
" Model of the vehicle " + model +
" Year of the vehicle: " + year;
return result;
}
}
Which instantiates make, model and year. Then once I was writing the driver class, the way I began was:
import java.util.Scanner;
public class PP43CarTest {
public static void main(String[] args) {
PP43Car car1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the model of the vehicle:");
car1.getModel();
}
}
But this class produces error and here is where I am stuck. Do I keep on going with this or is this what is meant by "instantiating and updating several objects?"
import java.util.Scanner;
public class PP43CarTest {
static PP43Car car1;
public static void main(String[] args) {
//Scanner scan = new Scanner(System.in);
car1 = new PP43Car("Millenia", "Mazda", 2011);
}
}
If the above code is correct, then can anyone show me how I can use the Scanner class to actually get the user input and update it that way because I would like to learn that as well?
Well, in your last fragment of code you are indeed instantiating an object, since you are doing:
car1 = new PP43Car("Millenia", "Mazda", 2011);
When you create a new object, you are creating a new instance of the class, so yes, you are instantiaing an object.
But you aren't updating it anywhere, because I think here updating means modifying the object, but you only create the object, not modify it...
Something like this would be an update:
car1.setYear(2013);
Since you are setting a different value for an attribute of the object, you are updating it...
EDIT: Try this code, it can't throw any exception, it's Java basics! I hope it clarifies your doubts...
public class PP43CarTest {
public static void main(String[] args) {
//Declaring objects
PP43Car car1;
PP43Car car2;
PP43Car car3;
//Instantiating objects
car1 = new PP43Car("Millenia", "Mazda", 2011);
car2 = new PP43Car("Aaaa", "Bbb", 2012);
car3 = new PP43Car("Ccc", "Ddd", 2012);
//Updating objects
car1.setMake("Xxx");
car1.setMake("Yyy");
car1.setYear(2013);
//Printing objects
System.out.println("CAR 1: " + car1.toString());
System.out.println("CAR 2: " + car2.toString());
System.out.println("CAR 3: " + car3.toString());
}
}

Categories