I'm trying to prevent user to add 2 attendee with the same passport I tried many things as making Boolean variable to check if attendee was added before or no but I have failed all of my attempts can't really think of a way to make this
public class Test {
public static void main(String[] args) {
try {
Workshop Available_Work_Shops = new Workshop();
Scanner sc = new Scanner(System.in);
String passportNumber, workshop;
boolean isAttendeeMatch;
ArrayList<Attendee> attendeeList = new ArrayList<>();
int choice;
do {
System.out.println("1. Add New Attendee");
System.out.println("2. Add Existing Attendee to Workshop");
System.out.println("3. Remove Attendee from Workshop");
System.out.println("4. Print WorkShop List");
System.out.println("5. Print All Attendees");
System.out.println("0. Close Program");
System.out.println("Please Enter a number to choose");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1 -> {
System.out.println();
System.out.println("Adding New Attendee");
System.out.println("____________________");
System.out.print("Please Enter Attendee Name: ");
String Attendee_name = sc.nextLine();
System.out.print("Please Enter Attendee Passport Number: ");
String Attendee_passport = sc.nextLine();
System.out.print("Please Enter Attendee Age: ");
String Attendee_Age = sc.nextLine();
System.out.print("Please Enter Attendee Phone Number: ");
String phone = sc.nextLine();
attendeeList.add(new Attendee(Attendee_name, Attendee_Age, Attendee_passport, phone));
for (Attendee attendee : attendeeList) {
if (attendeeList.contains(attendee.PassportNumber)) {
System.out.println("Existing User Found please enter '3' to remove the duplicate user");
}
}
}
The Issue
Let's focus on these two lines
...
for (Attendee attendee : attendeeList) {
if (attendeeList.contains(attendee.PassportNumber)) {
...
Since you've defined the attendeeList to be an ArrayList holding Attendee objects, you should be passing Attendee objects to attendeeList.contains(). While the contains() function does accept any Object, it will only return true if one of the List's elements .equals() the object you pass in.
The Solution
I'd recommend changing this block of code...
attendeeList.add(new Attendee(Attendee_name, Attendee_Age, Attendee_passport, phone));
for (Attendee attendee : attendeeList) {
if (attendeeList.contains(attendee.PassportNumber)) {
System.out.println("Existing User Found please enter '3' to remove the duplicate user");
}
}
... to something like this
Attendee potentialAttendee = new Attendee(Attendee_name, Attendee_Age, Attendee_passport, phone)
// Check if the potentialAttendee's passport number is already used by someone in the list.
boolean passportRegistered = false;
for (Attendee attendee : attendeeList) {
if (attendee.PassportNumber.equals(potentialAttendee.PassportNumber) {
System.out.println("That user passport number has already been registered. It can't be added again.");
passportRegistered = true;
}
}
// Only add the potentialAttendee if his/her passport number wasn't already used by someone in the list.
if (!passportRegistered) {
attendeeList.add(potentialAttendee);
}
The key difference is that you shouldn't add the potentialAttendee to the list until you've first validated that he/she meets the requirements to be added to that list.
Potential Enhancements
Store the Attendees in a HashMap instead of an ArrayList. If you key off of the PassportNumber, then by definition you can't have two participants with the same PassportNumber in the collection of attendees.
Java has a nice Streaming API that could make the validation even closer to a one liner.
Right off the bat, I see a few issues that would break the code:
You're adding the attendee to the list and then checking if it exists in the list afterwards (which it always will after adding it if checking correctly).
if (attendeeList.contains(attendee.PassportNumber)) will never return true because you're checking if the entire List has an object that is equal to the PassportNumber in it (as opposed to the PassportNumber in the object). It should be if(attendee.getPassportNumber().equals(Attendee_passport)).
Not sure how much of a beginner you are but it might also be useful to look into things like naming conventions (in general Java variables should be named with a lowercase first letter and each new word has an uppercase letter), using List<Attendee> as the declared variable type instead of ArrayList, and things like filtering lists using Java Streams to see if something exists already. Java also has Set as an alternative to List for when you only want to store unique values (there's other differences between List and Set so make sure you look into it if you want to use it).
Related
My main goal is to identify if a number enters is not duplicated in the list, else user needs to update a new number. The system will keep asking user to enter non duplicate numbers.
I am currently struggling to get the logic in order to check if my List contains a duplicate ID. If someone inputs a duplicate ID, then he will be prompted to re-enter a new number. The new number will be checked again until the system satisfies with no duplicate element. The following function returns an integer, which will be added to the List of type Course in the main method.
The following is the snippet of my function:
public static int ifExist(List<Course> courselist, Iterator<Course> itr, int personid) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
boolean found = false;
boolean flag = false;
int personid2 = personid;
String value = null;
while (itr.hasNext()) {
Course courseItr = itr.next();
if(courseItr.getPersonID() == personid) {
found = true;
flag = true;
while(found == true) {
System.out.print("No duplicate number is accepted. Please enter another number: ");
do {
// must be a digit from 1 - 10,000
String digit = "\\d{1,10000}";
value = input.nextLine();
flag = value.matches(digit);
if (!flag) System.out.print("Please a number only!: ");
} while (!flag);
personid2 = Integer.parseInt(value);
if(personid2 != courseItr.getPersonID()) {
found= false;
}
}
}
}
return personid2;
}
The output while executing the Course program can be shown below. Note that entering no 1 means adding a course list.
Please select your choice: 1
Enter the person ID: 1
Enter the person name: Alysa
Enter the title of the course: Maths
Enter the year of joining: 2021
Enter the fee of the course: 20.50
New Course has successfully been added.
Please select your choice: 1
Enter the person ID: 1
No duplicate number is accepted. Please enter another number: 1
No duplicate number is accepted. Please enter another number: 1
No duplicate number is accepted. Please enter another number: 1
No duplicate number is accepted. Please enter another number: 2
Enter the person name: Maria
Enter the title of the course: Biology
Enter the year of joining: 2021
Enter the fee of the course: 25.99
New Course has successfully been added.
Please select your choice: 1
Enter the person ID: 2
No duplicate number is accepted. Please enter another number: 2
No duplicate number is accepted. Please enter another number: 2
No duplicate number is accepted. Please enter another number: 2
No duplicate number is accepted. Please enter another number: 1
Enter the person name: Peter
Enter the title of the course: Chemistry
Enter the year of joining: 2021
Enter the fee of the course: 50.50
New Course has successfully been added.
As shown in the above, it shows that my ifExist method is not working (trying to get the logic right). The two persons have the same ID, such 1.
When I tried to display the Course List
Please select your choice: 3
Person ID: 1, Name: Alysa, Title: Maths, Year: 2021, Fee: $20.5.
Person ID: 2, Name: Maria, Title: Biology, Year: 2021, Fee: $25.99.
Person ID: 1, Name: Peter, Title: Chemistry, Year: 2021, Fee: $50.5.
I have googled it, but it seems that I either have to use Set to remove any duplicates or use equals/hashcode(). Nevertheless, I would be highly appreciated if any experienced java programmer to help clarify or provide any idea on how to resolve this problem.
NEWLY ADDED METHOD
public static void addCourse(List<Course> courselist, Course course) {
//check if the id is the same or not
ListIterator<Course> itr = courselist.listIterator();
try {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
int personid, year;
String author, title;
double fee;
System.out.print("\nEnter the person ID: ");
personid = input.nextInt();
personid = ifExist(booklist, itr, personid);
course.setPersonDd(personid);
...
...
...
courselist.add(new Course(personid, author, title, year, fee));
System.out.println("New Course has successfully been added.");
} catch {
}
}
Thank you. Look forward to hearing from fellow developers.
Regards,
Simone11
Regarding your first method
The problem lies in the iterator. When the user inputs 1 after 2, the iterator has already gone through the Course with the ID 1, so it is unable to detect duplicate IDs. Hence, every time the user inputs a new number, you must restart the iteration.
The List<Course> courselist parameter is unused.
With that said, this program is not logically optimized. The ifExists(,) method should solely work on searching for courses with the same ID. As for handling user input, it should be done completely outside of the method.
Here is an example of the ifExists(,) method
public static boolean ifExists(int id, Iterator<Course> iterator){
while (iterator.hasNext()) {
Course next = iterator.next();
if (next.id == id) return true;
}
return false;
}
Then in the main method, your messages to the user are based on the value returned by this method. Here is an example:
Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
while (ifExists(id)) {
System.out.println("Duplicated ID! Please try another number.");
id = scanner.nextInt();
} // If ifExists(id) returns false, continue to the code below to enter personal details
Regarding your second method
Use HashSet instead of List or Iterator. You can directly call HashSet.contains(Obj) to check whether a Course already exists in the collection, without looping through the items. Even though List also has this method, it loops through all the items, which is similar to what you are doing.
This is because HashSet orders items by their hash code instead of the order of being added, but List doesn't. So when you call the contains method, it looks for entry no. (insert hash code).
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
}
I'm trying to get some input from the user and store them into arraylist. The problem is I have to write the item twice to add an item into the list. I can't figure out why!
Instead of do-while loop use only while
while (true){
System.out.println("Enter a product");
String product = input.nextLine();
if (!product.equalsIgnoreCase("q"))
arrayList.add(product);
else
break;
}
Every time you write readLine(), a line is read. In this loop,
do {
System.out.println("Enter a product");
String product = input.nextLine();
arrayList.add(product);
}
while (!input.nextLine().equalsIgnoreCase("q"));
There are two occurrences of readLine(), so two lines are read every iteration. The first line is always added to the list and not checked against q, and the second is never added to the list, and always checked against q.
You should only do nextLine once:
while (true) {
System.out.println("Enter a product");
String product = input.nextLine(); // only this one time!
if (!product.equalsIgnoreCase("q")) {
arrayList.add(product);
} else {
break;
}
}
It happenes coz input.nextLine() makes java read the input. You should read the line and only then do the stuff:
Scanner input = new Scanner(System.in);
String product = input.nextLine();
System.out.println("Enter a product");
while (!product.equalsIgnoreCase("q")) {
arrayList.add(product);
System.out.println("Enter a product");
product = input.nextLine();
}
You can read the String values using input.next() once and have a while loop in place and read further values into your list only if the value is not equal to q.
If you have read it twice as in your case, one value is added to the list in your do part, and the value you read again in your while part is only compared to q and so to exit your code, you will be missing one value and adding another and have to give two q values one after another to exit it.
Also, since most of the other users have given there answers with nextLine instead of next you may want to check what next does and what nextLine does. In brief, if you enter names of products separated by a delimiter (default space), then with next, each value separated by the space is considered a product. Similarly, if you enter on different line as well. But, with nextLine, each line as a whole will be added as a new product. It depends on how you may want to achieve this as per your requirement.
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
Scanner input = new Scanner(System.in);
String product = input.next();
while(!product.equalsIgnoreCase("q")) {
arrayList.add(product);
product = input.next();
}
System.out.println("You wrote the following products \n");
for (String naam : arrayList) {
System.out.println(naam);
}
}
I am literally know and get the hang of the java right now and I'm writing the program that helps to records patient'd ID in the Hospital, i'll show the whole code first,then, I will tell where you will, here is the code
package hospitalsrecord;
import java.util.*;
import java.io.*;
public class HospitalsRecord {
public static Scanner read = new Scanner(System.in);
public static ArrayList nameList = new ArrayList();
public static ArrayList patientAge = new ArrayList();
public static ArrayList Disease = new ArrayList();
public static ArrayList dateHospitalized = new ArrayList();
public static ArrayList roomNumber = new ArrayList();
//adding patient function
public static void AddNewPatient () {
//Ask patient's name
System.out.println("Please enter patient's name:");
String patientName = read.next();
//Ask Patient's age
System.out.println("Please enter patient's age:");
int age = read.nextInt();
//Ask patient's illness
System.out.println("Please enter patient's Disease name (also include accidents eg. Leg broke by Car Accident):");
String illness = read.next();
//Ask patient Hospitalized date
System.out.println("Please enter patient's Hospitalized date(Total days not included):");
String HPTLdate = read.next();
//Ask patient's room number
System.out.println("Please enter patient's hospitalize room number(3 degits):");
int HRN = read.nextInt();
//Confirmation
System.out.println("Doctor, would you like to confirm the following(y/n)?");
System.out.println("Name:" + patientName);
System.out.println("Age:" + age);
System.out.println("Disease:" + illness);
System.out.println("Date Hospitalized (HPTLD):" + HPTLdate);
System.out.println("Room Number:" + HRN);
String Confirm = read.next();
if (Confirm.equals("y")) {
nameList.add(patientName);
patientAge.add(age);
Disease.add(illness);
dateHospitalized.add(HPTLdate);
roomNumber.add(HRN);
} else {
AddNewPatient();
}
}
//Searching patient that listed
public static void searchPatient (){
}
//remove the patient function
public static void removePatient() {
}
//text printing function when strat the program
public static void selectorPage(){
System.out.println("Hello Doctor, welcome to Hospital Recorder v1.0.0");
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
//text printing simmilar to selecterPage function but perform after function
public static void selecterPageAfterAction() {
System.out.println("Your action has been performed, doctor");
System.out.println("Would you like to perform another action?(y/n)");
choiceSelection = read.next();
if (choiceSelection.equals("y")){
System.out.println("If you want to add new patient into this recorder type: 'add' in the next blank line line");
System.out.println("If you want to search the patient list type: 'search' in the next blank line");
System.out.println("And, if you want to remove the patient that was out of hospitalizing type: 'remove' in the next blank line");
option = read.next();
}
}
//Selection var
public static String option;
public static String choiceSelection;
//Main program
public static void main(String[] args) {
selectorPage();
switch (option) {
case("add"): {
AddNewPatient();
break;
}
case("search"):{
searchPatient();
break;
}
case("remove"):{
removePatient();
break;
}
case("end"):{
break;
}
default: {
System.out.println("Please enter the indentified option");
break;
}
}
if (option.equalsIgnoreCase("end")){
}
}
}
I hope you guys can read every line because it was so so so so complex, but for someone who can read all of it, i'll know that you'll say I still need more time for hard working, no worry i'll spend sometime to get most knowledge from you guys first, but still working hard for program to complete while waiting for answers! anyway the point that I want you guys to focus at this point:
if (option.equalsIgnoreCase("end")){
}
It maybe too blank because I've just newly add it while i'm working on it. So, what I want to know is at the if statement I type option.equalsIgnoreCase("end"), Am I explain the computer to do the following?
1.Compare the the String variable options with the String"end"?
2.Tell the computer to do the action inside if statement's when the String option wasn't the word end?
And please tell me how this method work, i don't clearly understand it. I understand like this "It compare two strings if it wasn't the same then it's result is true" I know my explanation is wrong so could you please help me? thanks again for helping if you can.
option.equalsIgnoreCase("end") - equalsIgnoreCase will ignore whether string is in lower case or uppercase.
So it will enter into if block only when option variable has either end or END.
Your first assumption is correct, you are asking to compare String whether it is equal to end. But Second one is wrong, from above code it will enter and execute statements present inside if only when option is end/END.
If you want to go inside If block when the option is not end then add a not like this if(!option.equalsIgnoreCase("end")).
I Hope this clears your doubt!
The class String has two methods to compare one String to another.
See the example below:
public static void main(String[] args) {
String str1 = "beer";
String str2 = "Beer";
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
}
The first method equals() compares str1and str2and takes the case into consideration. Hence, the first comparison results in false, meaning Beer is not equal to beer.
The second method equalsIgnoreCase()does the same, except that it is not case-sensitive. Result of this comparison is true, meaning "ignoring the case, Beer is the same string as beer".
Hope this helps.
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
String newItem = inputread.next();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
This is my code, I'm just learning Java and trying to made a little "To-Do List" type program. As it stands, I can only add one word at a time. If, for example, I type "Pick Up Milk", the arrayList only stores "Pick".
I tried using inputread.nextLine() above, but then I get an "InputMismatchException". Any advice? I'm sure it's something simple.
Edited to include the whole class, per request:
public class ToDo {
Scanner inputread = new Scanner(System.in);
ArrayList<String> toDoList = new ArrayList<String>();
public void menu() {
clearConsole();
System.out.println("Welcome to the To-Do program.");
System.out.println();
System.out.println();
System.out.println("Please select an option from the following menu, using the number.:");
System.out.println("1- View To-Do List");
System.out.println("2- Add Item To List");
System.out.println("3- Remove Item From List");
int userinput = inputread.nextInt();
switch (userinput) {
case 1:
clearConsole();
displayList();
System.out.println();
System.out.println("This is your list. Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
break;
case 2:
clearConsole();
addItem();
break;
case 3:
clearConsole();
deleteItem();
break;
}
}
public void clearConsole() {
for (int i = 0; i < 25; i++) {
System.out.println();
}
}
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
String newItem = inputread.nextLine();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
public void displayList() {
if (toDoList.isEmpty()) {
System.out.println("For [REDACTED]'s sake, add an activity.");
} else {
for (String listItem: toDoList) {
System.out.println(listItem);
}
}
}
public void deleteItem() {
System.out.println("Please choose the number of the line you want to delete:");
displayList();
int userinput = inputread.nextInt();
int listPos = userinput - 1;
toDoList.remove(listPos);
System.out.println("That item has been deleted. Type any key and press Enter to continue.");
String discardMe = inputread.next();
menu();
}
}
I would suggest using a BufferedReader instead of the Scanner class. The problem with a Scanner is that it looks for tokens between white spaces and new lines, so when you add something like Go to the store, each token between the white spaces will get picked up, and you will end up with go to the store, rather than 1 large token. You can get input using the BufferedReader by declaring it using:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
Then, in your addItem() method, in a while(true) loop, you read the input from the reader, then check if it is empty or not. IF it is empty, then you break the loop and exit the function, otherwise add an item to your list.
System.out.println("Please type the item to add to the To-Do List"); // Output
while (true) { // Continue adding items until user just hits enter
String newItem = buf.readLine(); // read user input
if (newItem == null || newItem.isEmpty()) { // check if the user entered anything, or just hit enter
break; // If they didn't enter anything, then break the loop and drop out of the function
}
toDoList.add(newItem); // if they did enter something, add it to your to-do list
}
For example, to test this I used a main method:
public static BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
List<String> toDoList = new ArrayList<String>();
System.out.println("Please type the item to add to the To-Do List");
while (true) {
String newItem = buf.readLine();
if (newItem == null || newItem.isEmpty()) {
break;
}
toDoList.add(newItem);
}
System.out.println("Your item has been added! Type any key and press Enter to continue");
for (String s : toDoList) {
System.out.println(s);
}
}
Then, when prompted for input I entered:
Please type the item to add to the To-Do List
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife
And for output I got:
Your item has been added! Type any key and press Enter to continue
Go to the grocery store and get milk
Stop by the gym and pay membership fees
Pick up flowers for the wife
You have several problems in this code.
Let's first address your input issues.
In the menu, you read a number. When you use scanner.next(), scanner.nextInt() etc., it reads the following item up to - but not including - any white space or newline. So the white space or newline remain in the buffer waiting to be read.
Now, when you go to the addItem() and use nextLine(), it reads just that whitespace or newline. If it was just a newline (a Return you pressed), then you get an empty string, and you probably don't want to add that to the list. If you use next() it will skip that newline but... it will read just one word.
So you need to have a nextLine() after your nextInt() in the menu. After you read your integer, you'll clear the buffer up to and including the newline.
Then, inside the addItem() method, you'll be able to use nextLine() again, because it will now start on a fresh new line - and it will read the next line in its entirety.
Also, the discardMe part has to be with nextLine(), not with next(), otherwise it will not clear the end-of-line for the next operation.
Your other problem is something you didn't ask about. What you currently do is basically go into the menu, then go into an operation, then go into the menu, then an operation. You keep calling more and more functions, and you never return, or rather, you return from all when you display the list.
In time, this may cause a stack overflow.
The proper way to do this is not to call menu() from inside the operational methods, but rather, to have a loop in the menu() method, which shows the menu, calls the appropriate operational method, and when it returns (clears its space on the stack), loops back to the menu and so on. This keeps your stack nice and flat.
And of course, you should have a "Quit" option on your menu.
an example for Stultuskes idea:
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
System.out.println();
try (Scanner in = new Scanner(System.in)) {
while (in.hasNext()) {
String newItem = in.next();
toDoList.add(newItem);
System.out
.println("Your item has been added! Type any key and press Enter to continue");
}
}
System.out.println(toDoList);
}
public void addItem() {
System.out.println("Please type the item to add to the To-Do List");
//The skip gets over the leftover newline character
inputread.skip("\n");
String newItem = inputread.nextLine();
toDoList.add(newItem);
System.out.println("Your item has been added! Type any key and press Enter to continue");
String discardMe = inputread.next();
menu();
}
Putting in the skip fixed it for me. I want to thank you guys for your answers.
I created a class called Student and assigned it 3 values (StudentNumber, Course, Mark); I then assigned a created student (s) to an arrayList called studentsCourses.
This way each student takes up an index in the array. But how do I get the students back OUT of the arrayList... if that makes sense? I have them stored, but I don't know how to recall the information so that I can see it.
public static void main (String[]args){
ArrayList<Student> studentsCourses= new ArrayList<Student>();
String studentNumber="~";
String course="~";
int mark=0;
Student pat;
Student s=null;
do{
s=new Student();
System.out.println("Please Enter Your Student ID (type quit to Quit):\n");
studentNumber=keybrd.next();
s.setStudentNumber(studentNumber);
System.out.println("Please Enter Your Course ID:\n");
course=keybrd.next();
s.setCourse(course);
System.out.println("Please Enter Your Mark:\n");
mark=keybrd.nextInt();
s.setMark(mark);
s.printStates();
studentsCourses.add(s);
}while(!studentNumber.equals("quit"));
System.out.println(studentsCourses.size());
System.out.println(studentsCourses);
so if I wanted to assign the created student (pat) the state of index 1 how would I do that?
My one other issue (going along with this piece of code) is my sentinel. it does indeed quit when I type quit. but it finishes running through the "do" first. meaning I actually end up with a student who's number is "quit" course is whatever and mark is whatever.
How do I force it to break the do as soon as "quit" is typed?
"But how do I get the students back OUT of the arrayList... if that makes sense? I have them stored, but I don't know how to recall the information so that I can see it."
To get the data from arraylist:
for (Student student : studentsCourses) {
System.out.println(student.getStudentNumber());
System.out.println(student.getCourse());
System.out.println(student.getMarkr());
}
or
for (int i = 0; i < studentsCourses.size(); i++) {
Student student = studentsCourses.get(i);
System.out.println(student.getStudentNumber());
System.out.println(student.getCourse());
System.out.println(student.getMarkr());
}
to solve other issue, you can try:
do{
s=new Student();
System.out.println("Please Enter Your Student ID (type quit to Quit):\n");
studentNumber=keybrd.next();
if(studentNumber.equals("quit"))
break;
s.setStudentNumber(studentNumber);
System.out.println("Please Enter Your Course ID:\n");
course=keybrd.next();
s.setCourse(course);
System.out.println("Please Enter Your Mark:\n");
mark=keybrd.nextInt();
s.setMark(mark);
s.printStates();
studentsCourses.add(s);
}while(true);
The ArrayList is not an array... It's a List which uses arrays as its backing store.
The retrieval method from list is list.get(index)
Alternately, you can use some syntactic sugar to just loop over them
List<Student> students = new ArrayList<Student>();
// add students
for (Student student : students) {
// do something with student
}
Use get(int)method to retrieve an element.
Use add(int, E)method to insert an element at an index.
Try
System.out.println("Please Enter Your Student ID (type quit to Quit):\n");
studentNumber=keybrd.next();
while (!studentNumber.equals("quit")){
s=new Student();
s.setStudentNumber(studentNumber);
System.out.println("Please Enter Your Course ID:\n");
course=keybrd.next();
s.setCourse(course);
System.out.println("Please Enter Your Mark:\n");
mark=keybrd.nextInt();
s.setMark(mark);
s.printStates();
studentsCourses.add(s);
System.out.println("Please Enter Your Student ID (type quit to Quit):\n");
studentNumber=keybrd.next();
}
You can add a toString() method to your Students class :
#Override
public String toString()
{
return "\tStudentNumber: " + studentNumber
+ "\tCourse: " + course
+ "\tMarks: " + marks;
}
And then you can say :
System.out.println(studentsCourses);
As far as this is concerned :
How do I force it to break the do as soon as "quit" is typed?
This behaviour is because you are using do..while() ! Try using while instead.
There are two things you need to know:-
Firstly, you're using a do-while loop, which is an exit check loop, hence it will execute once atleast, before terminating. If you want to avoid it, try using a while loop.
Next, to retrieve all elements from the list, you can either use the list.get(index) or the for loop traversal as below:-
List<Student> students = new ArrayList<Student>();
for (Student student : students) {
// Do something with the student object.
}
Update:-
The for you've seen above, is actually Foreach loop. This is what it means
for each item in collection:
do something to item
Hence, the loop means,
for each item(student) in collection(students)
do something to item(student)
Now coming back to looping part. Forget everything, and just use a break;.
After this piece of code studentNumber=keybrd.next();, do a check and break the loop.
if(studentNumber.equals("quit")){
break;
}
Simple solution.
Why not use a hashmap with key as Student number and Object to that key as Student Object. In this way you could avoid duplication as well.
For the sentinel
// 1. Create a Scanner using the InputStream available.
Scanner scanner = new Scanner( System.in );
String input=null;
do{
// 2. Don't forget to prompt the user
System.out.print( "Type some data for the program: " );
// 3. Use the Scanner to read a line of text from the user.
input = scanner.nextLine();
// 4. Now, you can do anything with the input string that you need to.
// Like, output it to the user.
System.out.println( "input = " + input );
}while(!input.equalsIgnoreCase("quit"));