I need to be able to verify an age in the main class so for example if the name and age is added to the queue and when the person tries to leave if the age is less than 18 then a message appears saying "left because too young" or if the person is over 18 then a message appears saying "person left"
This is my main Class
public static void main(String[] args)
{
Queue q = new Queue();
Scanner k = new Scanner(System.in);
System.out.print("Join (j), leave (l) or end (e)? ");
String action = k.nextLine();
while (!action.equalsIgnoreCase("e"))
{
if (action.equalsIgnoreCase("j"))
{
System.out.print("Enter Name ");
String Name = k.nextLine();
System.out.print("Enter Age : ");
int Age = k.nextInt();
Person p1 = new Person(Name,Age);
q.add(p1);
System.out.println(Name + " Age " + Age + " Joined");
}
else if (action.equalsIgnoreCase("l"))
{
if (!q.isEmpty())
{
System.out.println(q.remove() + " Person Left");
}
else
{
System.out.println("Queue Empty");
}
}
else
{
System.out.println("Invalid operation");
}
System.out.print("Join (j), leave (l) or end (e)? ");
action = k.nextLine();
I also have a person class with the name and age and also a Queue Class.
Why can't you just add an if statement?
int Age = k.nextInt();
Person p1 = new Person(Name, Age);
q.add(p1);
if (Age < 18) {
q.remove(p1);
System.out.println("left because too young");
}
Related
I have an assignment where I'm supposed to get a name and phone number and store it in a linked list. However, when I'm printing out the list of 3 contacts, only the first contact is being printed. What am I doing wrong?
This is the file that was given to me with the main.
ContactList.java
public class ContactList
{
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String name;
String number;
ContactNode contact1;
ContactNode contact2;
ContactNode contact3;
System.out.println("Person 1");
System.out.println("Enter name:");
name = scnr.nextLine();
System.out.println("Enter phone number:");
number = scnr.nextLine();
System.out.println("You entered: " + name + ", " + number);
contact1 = new ContactNode(name, number);
System.out.println("Person 2");
System.out.println("Enter name:");
name = scnr.nextLine();
System.out.println("Enter phone number:");
number = scnr.nextLine();
System.out.println("You entered: " + name + ", " + number);
contact2 = new ContactNode(name, number);
System.out.println("Person 3");
System.out.println("Enter name:");
name = scnr.nextLine();
System.out.println("Enter phone number:");
number = scnr.nextLine();
System.out.println("You entered: " + name + ", " + number);
contact3 = new ContactNode(name, number);
ContactNode temp = contact1;
contact3.insertAfter(contact2);
contact2.insertAfter(contact1);
System.out.println("CONTACT LIST:");
while (temp!= null)
{
temp.printContactNode();
temp = temp.getNext();
System.out.println();
}
}
}
This is the file that I was to implement.
ContactNode.java
public class ContactNode
{
private String contactName;
private String contactPhoneNumber;
private ContactNode nextNodePtr;
// constructor
public ContactNode(String name, String num)
{
contactName = name;
contactPhoneNumber = num;
nextNodePtr = null;
}
public String getName()
{
return contactName;
}
public String getPhoneNumber()
{
return contactPhoneNumber;
}
public void insertAfter(ContactNode nodeLoc)
{
ContactNode tmpNext;
tmpNext = this.nextNodePtr;
this.nextNodePtr = nodeLoc;
nodeLoc = tmpNext;
}
public ContactNode getNext()
{
return this.nextNodePtr;
}
public void printContactNode()
{
do
{
System.out.println("Name: " + this.contactName);
System.out.println("Phone number: " + this.contactPhoneNumber);
this.getNext();
} while(getNext() != null);
}
}
In your do while loop, there isn't any logic to move onto the next contact. Calling this.getNext() won't accomplish anything if you're not referencing the result. What you're probably looking for is something like this:
ContactNode current = this;
do {
// Print
current = current.getNext();
} while(current != null);
To solve problems like this in the future, you should probably take a look at what your code is doing line by line. For example, say we have two contacts (contact 1 and contact 2). Then your code will print the first contact information, then retrieve contact 2 (with this.getNext()) but not do anything with it, then check whether getNext() (contact 2) is null, which it isn't. Then the loop will repeat and the same process will happen again. Your code is never moving on.
Trying to make it so if the user types "end", in the second input which is "Enter the first name of student", the loop automatically assigns each object in the array the attributes of "null" for id and name, and 0 for age and id, as well as breaking the outerloop. However, I get the error java.lang.NullPointerException.
Any help would be appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
System.out.println("Number of students is " + numberof);
Student Studentz[] = new Student[numberof];
outerloop:
for (int i = 0; i < numberof; ++i) {
Studentz[i] = new Student();
System.out.println("Enter first name of student " + (i + 1));
Scanner myObj1 = new Scanner(System.in);
String firstname = myObj1.nextLine();
System.out.println("Firstname is: " + firstname);
if (firstname.equals("end")) {
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null");
Studentz[g].Setlast("null");
Studentz[g].Setage(0);
Studentz[g].Setid(0);
}
break outerloop;
} else {
Studentz[i].Setfirst(firstname);
System.out.println("Enter last name of student " + (i + 1));
Scanner myObj2 = new Scanner(System.in);
String lastname = myObj2.nextLine();
System.out.println("Last name is: " + lastname);
Studentz[i].Setlast(lastname);;
System.out.println("Enter age of student " + (i + 1));
Scanner myObj3 = new Scanner(System.in);
int nazca = myObj3.nextInt();
System.out.println("Age is: " + nazca);
Studentz[i].Setage(nazca);
System.out.println("Enter ID of student " + (i + 1));
Scanner myObj4 = new Scanner(System.in);
int nazca1 = myObj4.nextInt();
System.out.println("ID is: " + nazca1);
Studentz[i].Setid(nazca1);
}
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
}
}
}
public class Student {
private String first;
private String last;
private int age;
private int id;
public int getid() {
return
this.id;
}
public void Studentss(String f, String l, int a, int i) {
first = f;
last = l;
age = a;
id = i;
}
public void Setfirst(String z) {
this.first = z;
}
public void Setlast(String za) {
this.last = za;
}
public void Setage(int zb) {
this.age = zb;
}
public void Setid(int zc) {
this.id = zc;
}
public String Snake() {
String snek = "Name is " + this.first + " " + this.last + " , Age is " + this.age + " ,ID is " + this.id;
return snek;
}
}
you fail here because you try to print students data before you initialized all elements of Studentz array:
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
also your code fails here by the same reason:
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null"); // NPE - no Student created yet in the array
Some Possibly Helpful Tips:
Follow Java naming rules for your variables and method names, Studentz should be studentz, even for your Arrays. I know...your tired of reading that but as you progress, you'll see how beneficial it really is.
If you can, don't use multiple Scanner objects, there is no need for that in your use-case. Declare one Scanner object and stick with it. You're probably doing this because you are using the nextLine() method after the nextInt() method and you're finding that it skips the first name prompt and provides a Null String (""). This happens because the nextInt() method does not consume the newline character when the Enter key is hit. To solve this problem you would either, place the code line myObj.nextLine(); directly under the int numberof = myObj.nextInt(); code line:
int numberof = myObj.nextInt();
myObj.nextLine(); // Consume ENTER key hit
or don't use the nextInt() method at all. Instead just stick with the nextLine() method and not worry about consumption:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
It's always a good idea to validate any input from the User (as shown above), even if they're in a for loop. Give the User an opportunity to make a correct entry, after all, typo's do happen.
Get rid of the outerLoop: label. As a matter of fact, try avoid ever using them if you can....and you can. It would only be on a relatively rare occasion where you might ever need one.
Give your variables meaningful names, at least to some extent. This can benefit you later on down the road when you want to read your old code in the future.
In your Student class you made yourself a this real nice method named Studentss(). Well, I think it should be a constructor instead and save yourself a lot of code entry for calls to Setter methods. After all, that's mostly what the constructor is for. Your Student class constructor can look like this:
public Student(String firstName, String lastName, int age, int id) {
this.first = firstName;
this.last = lastName;
this.age = age;
this.id = id;
}
And be used like this. You will notice that upon each iteration of the outer for loop, all the prompt answers are placed within variables then at the end of all those prompts the constructor is used instantiate a student object, for example:
studentz[i] = new Student(firstname, lastname, age, id);
Doing it this way mean that there is no need to make calls to Setter methods. There is nothing wrong with making setter calls, it's just easier using the constructor. This is demonstrated below:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
for (int i = 0; i < numberof; ++i) {
String firstname = "null";
String lastname = "null";
int age = 0;
int id = 0;
boolean exitOuterForLoop = false;
// Student First Name Prompt:
// (with option to End and default remaining to null's and 0's)
while (firstname.equals("null")) {
System.out.println("Enter first name of student " + (i + 1) + " (End to stop):");
firstname = myObj.nextLine();
if (firstname.equalsIgnoreCase("end")) {
firstname = "null";
//Make all remaining Student instances null and 0
for (int g = i; g < numberof; ++g) {
studentz[g] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
exitOuterForLoop = true;
break; // Exit this 'while' loop
}
// Validate first name (no numbers or crazy characters)
if (!firstname.matches("(?i)[a-z']+")) {
System.err.println("Invalid First Name! (" + firstname + ") Try Again...");
firstname = "null";
}
}
if (exitOuterForLoop) {
break; // Exit this outer 'for' loop.
}
System.out.println("Firstname is: " + firstname);
// Student Last Name Prompt
while (lastname.equals("null")) {
System.out.println("Enter last name of student " + (i + 1));
lastname = myObj.nextLine();
// Validate last name (no numbers or crazy characters)
if (!lastname.matches("(?i)[a-z']+")) {
System.err.println("Invalid Last Name! (" + lastname + ") Try Again...");
lastname = "null";
}
}
System.out.println("Last name is: " + lastname);
// Student Age Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter age of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid Age Supplied! (" + val + ") Try Again...");
val = "";
}
}
age = Integer.parseInt(val);
System.out.println("Student age is: " + age);
// Student ID Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter ID of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid ID Supplied! (" + val + ") Try Again...");
val = "";
}
}
id = Integer.parseInt(val);
System.out.println("Student ID is: " + id);
studentz[i] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
// Display the instances of Student contained within the 'studentz[]' array.
for (int c = 0; c < numberof; ++c) {
System.out.println(studentz[c].toString());
}
The snake() method is actually just another toString() method and there is nothing wrong with that however you might want to consider using StringBuilder class to create the returned string rather than doing concatenations, for example:
public String snake() {
return new StringBuilder("Name is ").append(this.first).append(" ").append(this.last)
.append(" , Age is ").append(this.age).append(" , ID is ")
.append(this.id).toString();
}
Not overly important here but it can save you memory if you do a lot concatenating with many large strings.
I am getting null output along when i am getting to string method in my program output.
//Main Method
package studentDatabaseApp;
import java.util.Scanner;
public class StudentDatabaseApp {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of Students: ");
int numOfStudents = scan.nextInt();
Student[] students = new Student[numOfStudents];
for(int n =0; n < numOfStudents; n++) {
students[n] = new Student();
students[n].enroll();
students[n].payTution();
}
for(int n =0; n < numOfStudents; n++) {
System.out.println(students[n].toString());
}
}
}
//Student Class Code
package studentDatabaseApp;
import java.util.Scanner;
public class Student {
private String firstName;
private String lastName;
private int gradeYear = 0;
private String studentID;
private String courses;
private static int courseCost = 600;
private int tutionBalance = 0;
private static int id = 1000;
//Constructor to enter student name and year for each student
public Student() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Student First Name: ");
this.firstName = scan.nextLine();
System.out.print("Enter Student Last Name: ");
this.lastName = scan.nextLine();
System.out.print("1 - Freshmen\n2 - Sophmore\n3 - Junior\n4 - Senior\nEnter Student Grade Year: ");
this.gradeYear = scan.nextInt();
//Setting student id
setStudentID();
}
//Unique id and student grade level
private void setStudentID() {
id++;
this.studentID = gradeYear + "" + id;
}
//Create courses so student can enroll
public void enroll() {
do {
System.out.print("Enter course to enroll (Q to Quit): ");
Scanner in = new Scanner(System.in);
String course = in.nextLine();
if(!course.equals("Q")) {
courses = courses + ", " + course;
tutionBalance = tutionBalance + courseCost;
}
else {
break;
}
}while(1 != 0);
}
//Student should able to view their balance and pay the tution
public void viewBalance() {
System.out.println("BALANCE TOTAL: " + tutionBalance);
}
//Total balance
public void payTution() {
viewBalance();
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter your payment: ");
int tutionPaid = scan.nextInt();
tutionBalance = tutionBalance - tutionPaid;
viewBalance();
}
//Student status with their name, ID, course enrolled and balance
#Override
public String toString() {
return "\nSTUDENT NAME: " + firstName + " " + lastName +
"\nGRADE LEVEL: " + gradeYear + " " + "\nSTUDENT ID: " + studentID +
"\nCOURSES ENROLLED: " + courses +
"\nTUTION BALANCE: " + tutionBalance;
}
}
//Console Output
Enter number of Students: 1
Enter Student First Name: bilal
Enter Student Last Name: mujahid
1 - Freshmen
2 - Sophmore
3 - Junior
4 - Senior
Enter Student Grade Year: 4
Enter course to enroll (Q to Quit): Eng 101
Enter course to enroll (Q to Quit): Math 101
Enter course to enroll (Q to Quit): Q
BALANCE TOTAL: 1200
Enter your payment: 1000
BALANCE TOTAL: 200
STUDENT NAME: bilal mujahid
GRADE LEVEL: 4
STUDENT ID: 41001
COURSES ENROLLED: null, Eng 101, Math 101
TUTION BALANCE: 200
The problem is with
private String courses;
You use
courses = courses + course;
Courses is null since it is never initialized. Try changing it to
private String courses = “”;
(This will cause it to have a extra comma in the beginning which you can easily just substring off)
Initialise it with course the first time
if(!course.equals("Q")) {
courses = coursers == null ? course : courses + ", " + course;
...
package michael.week.pkg5;
class Employee {
String Fname ;
String Lname;
String PhoneNum;
String Address;
void setFirst(String First){
Fname = First ;
}
void setlast(String Last){
Lname = Last ;
}
void setAddress (String address){
Address = address ;
}
void setPhone (String Phone){
PhoneNum = Phone ;
}
void display (){
System.out.println ("the Fist name is :"+ Fname + " , the last name is : " + Lname + " ,the address is : "+ Address+ " ,the phone is : "+ PhoneNum);
}
}
package michael.week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MichaelWeek5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Stck {
Employee stck [] = new Employee[10];
int x ;
void stck (){
x= -1 ;
}
Employee push (Employee item){
if (x == 9){
System.out.println ("Stack is full");
}else stck[++x] = item ;
return stck[x];
}
Employee pop (){
if (x <0){
System.out.println (" Stack underflow");
return stck [x];
}else
return stck[x++];
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
String info2 = null ;
Stck obj = new Stck();
Employee obj2 = new Employee ();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.stck ();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
System.out.println ("please enter Employee last name name :");
info = br.readLine();
System.out.println ("please enter Employee address :");
info = br.readLine();
System.out.println ("please enter Employee phone number :");
info = br.readLine();
}
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
Greetings,
i am new to java and i am working on this program....... i need to know how can i push the data to the stck ?
note : the push's parameter is type employee, and Employee contains First , Last, Phone , and address. how i can push each of them ?
here is what i did , and my instructor refused it
package week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Week5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Employee {
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
void increment(){
x++;
}
void PushFirst(String First){
Fname[x] = First ;
}
void Pushlast(String Last){
Lname [x] = Last ;
}
void PushPhone (String Phone){
PhoneNum [x] = Phone ;
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
}
void PushAddress (String address){
Address [x] = address ;
}
void pop (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
x--;
}
}
void display (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
for (int q = 0 ; q <=x ; q++){
System.out.println ((q+1)+"- "+"the First name is :"+ Fname [q]+ " , the last name is : " + Lname [q] + " ,the address is : "+ Address[q] + " ,the phone is : "+ PhoneNum[q]);
}
}
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
Employee obj = new Employee();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter display to display all employees list");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.increment();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
obj.PushFirst(info);
System.out.println ("please enter Employee last name name :");
info = br.readLine();
obj.Pushlast(info);
System.out.println ("please enter Employee address :");
info = br.readLine();
obj.PushAddress(info);
System.out.println ("please enter Employee phone number :");
info = br.readLine();
obj.PushPhone(info);}
} else if(choice.equals("display")){
obj.display();
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
You would need to create a stack of employees and then you can push the whole employee object on to the stack.
import java.util.Stack;
...
Employee emp = new Employee();
Stack<Employee> stack = new Stack<Employee>();
stack.push(emp);
after creating an object to the class say (here stck) which will hold the data by calling method ex shown below
class std
{
int id;
string name;
public:
void set_id(int i)
{
id=i;
}
void set_name(string n)
{
name = n;
}
void disp()
{
system.out.println("name"+name+" and id = "+id);
}
};
main()
{
std s = new std();
s.set_id(1);
s.set_name("sunmoon");
s.disp();
}
so here you can observe that s is considered as stack and we pushed one person details as like you can create array of object and push n number of person details.
You have several issues in how you've modeled the data.
Issue #1 (The biggest issue of all):
An Employee should not have any internal representation of the stack. Think objects in the real world. In your example, each Employee should have:
a first name
last name
address
phone number
So the member fields :
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
do not belong. This leads us to...
Issue #2 : The way you've modeled the Stack only allows for a fixed number of entries - 10 in your case). This is not how a stack should work. Read up on what a Stack is if you are uncertain. You can model a Stack in Java using a LinkedList - or use the built in Stack that Java provides. If you decide to create your own version, the important operations that need to be created are:
push
pop
isEmpty
My advice is to start by modelling the employee and pratice by pushing and popping them off of a built in Stack from the JDK until you really understand the operations before you try to create your own.
So I'm doing a TUI and this was my first iteration.
package bulb.classes;
import java.util.Scanner;
import java.util.ArrayList;
public class RoomTUI {
private ArrayList<Room> rooms;
Scanner scan = new Scanner (System.in);
private int userNumber;
private String userAnswer;
public void run() {
rooms = new ArrayList<Room>();
introduction();
userNumber = 0;
options();
while(userNumber < 5) {
if(userNumber == 1) {
newRoom();
}
if(userNumber == 2) {
addBulbToRoom();
}
if(userNumber == 3) {
clickAllBulbsInRoom();
}
if(userNumber == 4) {
printDescriptionOfBulbs();
}
}
System.out.println("Goodbye");
}
public int getUserInt(String aString) {
System.out.println(aString);
userAnswer = scan.nextLine();
userNumber = Integer.parseInt(userAnswer);
return userNumber;
}
public void displayRooms() {
System.out.println("Possible rooms to choose from.");
String tempString = "";
int roomIndex = 0;
for (int i = 0; i < rooms.size(); i++) {
tempString = tempString + "Room " + roomIndex++ + ": " + rooms.get(i).getDescription() + "\n";
}
System.out.println(tempString);
}
public void introduction() {
System.out.println("Welcome! With this program you can make rooms and design and place the light bulbs for each room you create.");
}
public void options() {
System.out.println("1 : Create a new Room");
System.out.println("2 : Add a bulb to an existing room");
System.out.println("3 : Click all of the bulbs in a particular room");
System.out.println("4 : Display a description of all bulbs in a particular room");
System.out.println("5 : Quit");
getUserInt("What would you like to do?");
}
public void newRoom() {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
rooms.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
public void addBulbToRoom() {
displayRooms();
System.out.println("Which room do you want the bulb in?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println("Please enter the blub's color.");
String color = scan.nextLine();
System.out.println("Please enter the blub's increment amount.");
String incrementS = scan.nextLine();
int incrementI = Integer.parseInt(incrementS);
ThreeWayBulb aBulb = new ThreeWayBulb(color, incrementI);
rooms.get(choiceNumber).addBulb(aBulb);
System.out.println("A " + color + " bulb with and increment of " + incrementI + " was added.");
options();
}
public void clickAllBulbsInRoom() {
displayRooms();
System.out.println("Which room do you want the bulbs clicked?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
rooms.get(choiceNumber).clickAllBulbs();
System.out.println("The bulbs in " + rooms.get(choiceNumber).getDescription() + " have been clicked.");
options();
}
public void printDescriptionOfBulbs() {
displayRooms();
System.out.println("Please enter a room number.");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println(rooms.get(choiceNumber).getDescription() + " with " + rooms.get(choiceNumber).returnSize() + " bulbs: " + "\n" + rooms.get(choiceNumber).toString());
options();
}
}
My instructor wants me to do this without instance variables He said if a method needs the ArrayList that I should make it a parameter and have no instance variables in my TUI. I can't for the life of me figure out how to do that. Also, making it static work fly either. Thanks for any help you can give.
He wants you to declare the ArrayList from a central location (such as the main thread) and then pass it as an argument to the functions that use it. This way if you were to take methods and put them in different classes then it wouldn't break because they're not dependent on this class.
For example if we take your newRoom class:
public void newRoom(List<Room> roomList) {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
roomList.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
EDIT: The easiest way to achieve this is to probably move the declaration of rooms to within your run method. Now for each location in the code that reports "unknown variable rooms" you can modify the function to take an ArrayList as a parameter.
Well, eliminating userNumber and userAnswer as members is trivial; their usage is very localized.
For the list, just pass it around after creating it in your main loop.
The scanner is used multiple places; it could also be passed around, I suppose.