Comparing elements of ArrayList in loop gives unexpected result? - java

The following code checks only the first item in the ArrayList. When I type in an item that is in the ArrayList but not in the first position, I get my error message as "Please enter a valid name".
How can I fix this? Thank you!
Here is my code:
private ArrayList<Account> accounts = new ArrayList<>();
for(Account a : accounts)
{
while(true)
{
System.out.printf("Customer name: ");
String customerName = scanner.next();
if(customerName.equals(a.getName()))
{
System.out.println("You entered " + a.getName());
break;
}
else
{
System.out.println("Please enter a valid name");
}
}
}

You have to break from while. When you iterating on list you have to think about logic. Its can be like this code ;
ArrayList<Account> accounts = new ArrayList<>();
boolean isMatched = false;
while (true) {
for (Account account : accounts) {
System.out.printf("Customer name: ");
String customerName = scanner.next();
if (customerName.equals(account.getName())) {
isMatched = true;
break;
}
}
if (isMatched) {
System.out.println("You entered " + account.getName());
break;
}
System.out.println("Please enter a valid name");
}
PS: boolean value to when found the customer name for ending while loop.

The inner loop does do that:
while(true) {
has no purpose here. It simply keeps looping inside the outer loop, therefore always comparing against the same a account!
Basically you have to swap the two loops!

The problem is the infinite while loop.
while(true)
This loop breaks only when customerName == firstElement.Name, else it is an infinite loop. Instead I think what you want to try is moving the while loop outside the for loop. So the code will look something like this.
private ArrayList<Account> accounts = new ArrayList<>();
while(true)
{
System.out.printf("Customer name: ");
String customerName = scanner.next();
for(Account a : accounts){
if(customerName.equals(a.getName())){
System.out.println("You entered " + a.getName());
break;
}else{
System.out.println("Please enter a valid name");
}
}
}

The problem you have it's because you are only checking the first element all the time. Just after you entering your first element, (and breaking your loop while(1)) you will pass to the second one.
Imagine you have in your arrayList
"hello", "bye"
You'll be inside your loop until texting the first element ("hello").
Solution:
while(true)
{
System.out.printf("Customer name: ");
String customerName = scanner.next();
if (accounts.contains(customerName)){
System.out.println("You entered " + customerName);
break;
}
else{
System.out.println("Please enter a valid name");
}
}

Related

How to give each student a unique ID after being created by the user on JAVA program

I am working on a school project that basically allows the user to create, edit or view students. Once a student is created, they each get assigned a unique ID like 1, 2, 3, etc. All the functionally of creation, editing and displaying is working but I am stuck on have to give them a unique ID after created. Here is the code I have and in the // commented areas is what I attempted to do but I am not sure if its right. Any ideas will be very appreciated.
import java.util.Scanner;
import java.io.*;
public class MidTermProject {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.println("Here is the sample of menu choices for Main Menu.");
System.out.println("\nWelcome to University Enrollment" + "\n1. Create Student" + "\n2. Edit Student" + "\n3. Display Student" + "\n0. --- Quit ---");
System.out.println("Please enter a valid choice(1-10, 0 to Quit) :");
int userInput = keyboard.nextInt();
if(userInput == 1) {
CreateStudent();
} else if(userInput == 2) {
EdithStudent();
} else if(userInput == 3) {
DisplayStudent();
} else if(userInput == 0) {
System.out.print("Done");
} else {
System.out.println("Invalid Option, Please try again.");
userInput = keyboard.nextInt();
if(userInput == 1) {
CreateStudent();
} else if(userInput == 2) {
EditStudent();
} else if(userInput == 3) {
DisplayStudent();
} else if(userInput == 0) {
System.out.print("Done");
}
}
}
public static void CreateStudent() throws IOException {
String FullName;
String address;
String city;
String state;
int StudentID;
Scanner keyboard = new Scanner(System.in);
FileOutputStream fstream =
new FileOutputStream("StudentInfo.dat");
DataOutputStream outputFile =
new DataOutputStream(fstream);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
outputFile.writeUTF(FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
outputFile.writeUTF(address);
System.out.print("City: ");
city = keyboard.nextLine();
outputFile.writeUTF(city);
System.out.print("State: ");
state = keyboard.nextLine();
outputFile.writeUTF(state);
//allowed the user to select their own ID number
System.out.print("Please get a Student ID(1-10): ");
//Store the selected number on StudentID
StudentID = keyboard.nextInt();
//The for loop will increment index each time a user is created
for(int index = 0; index == StudentID; index++) {
//The if statement will compare index and StudentID, if equal will ask the user to enter a different number
if(index == StudentID) {
System.out.print("The selected ID has been selected already, Please select a different ID");
StudentID = keyboard.nextInt();
}
}
//write the number in the file
outputFile.writeInt(StudentID);
System.out.print("Successfully Created");
}
public static void EditStudent() throws IOException {
String editName;
String editaddress;
String editCity;
String editState;
Scanner keyboard = new Scanner(System.in);
RandomAccessFile file =
new RandomAccessFile("StudentInfo.dat", "rw");
file.seek(0);
System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
editName = keyboard.nextLine();
file.writeUTF(editName);
System.out.print("Address: ");
editaddress = keyboard.nextLine();
file.writeUTF(editaddress);
System.out.print("City: ");
editCity = keyboard.nextLine();
file.writeUTF(editCity);
System.out.print("State: ");
editState = keyboard.nextLine();
file.writeUTF(editState);
file.close();
System.out.print("Successfully Edited");
}
public static void DisplayStudent() throws IOException {
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
DataInputStream inputFile = new DataInputStream(fstream);
String student;
boolean endOfFile = false;
while(!endOfFile)
{
try
{
student = inputFile.readUTF();
System.out.print(student + " ");
}
catch (EOFException e)
{
endOfFile = true;
}
}
System.out.println("\nDone");
inputFile.close();
}
Firstly, following Java naming conventions makes your code more readable. So use lowercase first when naming a variable: studentId rather than StudentId. Initial-caps is for class names.
In your create student method, your for loop makes no sense.
for(int index = 0; index == StudentID; index++) {
//The if statement will compare index and StudentID, if equal will ask the user to enter a different number
if(index == StudentID) {
System.out.print("The selected ID has been selected already, Please select a different ID");
StudentID = keyboard.nextInt();
}
}
A for loop simply increments the index defined in the first clause, stepping the increment according to the third clause, until the second clause proves true.
So in your code, if the user enters 4, your loop counts 0, 1, 2, 3, 4 «bingo». Now that we reached the user’s specified number, we go on to ask them for another number. And we’re done. But that process is illogical.
That code fails to accomplish your goal of checking for existing students. You need to review all existing students one-by-one. Compare each existing student ID against the desired ID. Only after exhausting the list of all known students should we use the desired ID. If we find a match on an existing student, then we break out of the loop to ask the user for another choice of ID. And we need another outer loop to continue this “ask, search, ask again if needed” process until an unused desired ID is determined.
Big tip: If you write out your problem statement and solution attempt as plain prose, similar to what I just did in the paragraph above, your programming will go more smoothly. And your written prose will be fodder for writing helpful comments in your source code.

How can I get a multidimensional array to loop with string input?

Basically I'm making a program that reads from a multidimensional array to display it's corresponding information. What I want to do is make it so the while loop will continue to tell me I'm putting in the wrong class ID's until you put in a correct Class ID.
do
{
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for(int x = 0; x <= classes.length; ++x)
{
if(name.equals(classes[x][0]))
{
i = true;
System.out.println("Course info: " + classes [x][0]);
System.out.println(classes[x][1]);
System.out.println(classes[x][2]);
x = classes.length;
}
else{
System.out.println("Wrong course id");
i = false;
input.next();
}
}
}
while (!(i));
System.out.println("This is the end of the program!");
System.exit(0);
First of all, try to keep good naming conventions. i is bad name for a flag variable. Name it boolean found or something. It will not only help other people read and understand your code, but it will help you in order find the logic you have to use as well.
Now, since you have input.next(); in else part, i guess you want to ask again for user input, until a something is found. So, a name = input.nextLine(); is required again in order to take new input. But in your case the else part can be removed completely and let the do-while do the work.
An example:
public class Classes {
private static final String[][] CLASSES = { { "Maths", "info" }, { "History", "info" }, { "Biology", "info" } };
public static void main(String[] args) {
boolean found = false;
String name;
Scanner input = new Scanner(System.in);
do {
System.out.println("Please enter the name of your course to display it's information");
name = input.nextLine();
for (int i = 0; i < CLASSES.length; i++) {
if (name.equals(CLASSES[i][0])) {
found = true;
System.out.println("Course info: " + CLASSES[i][0]);
System.out.println(CLASSES[i][1]);
// System.out.println(CLASSES[i][2]); //My CLASSES array, does not have 3 columns
break;// exit for loop
}
}
if (!found)
System.out.println("Wrong course id");
} while (!found);
input.close();
System.out.println("This is the end of the program!");
}
}

for loop - looping more than its supposed to?

public static void choice( String arrayString[], double arrayReal[])
{
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("1.display mark");
System.out.println("2.exit");
choice = sc.nextInt();
while (choice !=2 && choice != 1)
{
System.out.println("invalid input enter again");
choice = sc.nextInt();
}
switch (choice)
{
case 1:
output(arrayString, arrayReal);
break;
case 2:
System.out.println("exiting");
break;
default:
System.out.println("invalid choice choose between 1 and 2");
choice = sc.nextInt();
}
}
public static void output(String arrayString[], double arrayReal[])
{
String name;
Scanner sc = new Scanner(System.in);
for (int i=0;i<arrayString.length;i++)
{
System.out.println(arrayString[i]);
}
System.out.println("enter stident name");
name = sc.nextLine();
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
for (int j=0;j<arrayString.length;j++)
{
if (arrayString[j].equals(name))
{
System.out.println("mark of " + arrayString[j] + "is " + arrayReal[j]);
}
}
im trying to validate the student name and if it doesnt equal to any of the names in the array return back to the menu. it does go back to the menu but the problem is after going back to the menu even if i type the correct student name if keps going back to the menu. i thought for loops were supposed to loop set amount of times and pass to the next code?? is that right? also is my approach correct? ive tried putting if else in the last for loop but that didnt end up as i wanted it to as well. any help is appreciated thanks!
EDIT-
thanks for spotting the mistake. fixed !arrayString.equals(name) to !arrayString[k].equals(name) but still the same problem
Your problem ist here:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString.equals(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
}
You are comparing an Array String[] arrayString with a String name. They are never going to be treated as equal and therefor your choice method is allways called.
Also the whole loop is totally pointless as you never use your loop index k for anything.
You don't need a loop here at all. Instead you can simply convert the String array to a temporary list and check if it contains your input:
if(!Arrays.asList(arrayString).contains(name))
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}
Edit:
here a short main Method that can be used for testing:
public static void main(final String[] args) {
final String[] test = { "Mark", "Peter" };
final double[] test2 = { 1, 2 };
choice(test, test2);
}
Input/Output:
OUTPUT: 1.display mark
OUTPUT:2.exit
INPUT: 1
OUTPUT: Mark
OUTPUT: Peter
OUTPUT: enter stident name
INPUT: Mark
OUTPUT: mark of Markis 1.0
The logic at this part, after adding the index, is still wrong:
for (int k=0;k<arrayString.length;k++)
{
if(!arrayString[k].equals(name))
{
System.out.println("invalid name");
...
}
}
this will print "invalid name" for every name in the list that is not the given name. Example: if the first name in the array does not match, you will get a message (and choice called), no matter if the second entry matches.
One way is to search the whole array until you find the name and then act on the result:
boolean found = false;
for (int k=0;k<arrayString.length;k++)
{
if(arrayString[k].equals(name))
{
found = true;
break; // stop searching
}
}
if (!found)
{
System.out.println("invalid name");
choice(arrayString, arrayReal);
}

Code doesn't continue after the do-while loop?

I have began to learn Java in my AS level computing class, and have really taken to the first DIY task we have been set.
I have used a do-while statement to see if the input username from the user is in the array "names"- if it's not, it requests to re-enter the username, until a correct one is inserted. I have also set up a boolean, so when a correct username is entered, it cancels the do-while loop and continues with code - but it doesn't.
String[] names = {"mckeownl", "heardj", "williamsc"};
String[] attendance = {"yes", "no", "yes"};
int[] grade = {96, 66, 73};
boolean loggedin = false;
Scanner user_input = new Scanner(System.in);
String login;
login = user_input.next();
do { // beginning of while - login
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ");
if (Arrays.asList(names).contains(login)) {
System.out.println("Student selected: "+login+".");
loggedin = true;
}
else {
System.out.println("Incorrect student name! Please try again.");
loggedin = false;
}
} while ( ! loggedin);
if (login.equals(names[0])) {
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
}
else {
System.out.println("poo");
}
}
}
The output for a correct name is ;
"Insert student's surname followed by the first letter
of their first name (e.g John Smith = smithj): mckeownl
Student selected: mckeownl."
Why isn't the final if statement output?
You should be asking for the login inside the loop.
You shouldn't set the loggedin variable to false if it fails. Just give text that it failed, then it'll return to the top and ask for login again.
You can have multiple lines in a method call. So you could have:
System.out.println("Insert student's surname followed by the first letter " +
"of their first name (e.g John Smith = smithj): ");
Instead of:
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ");
put login = user_input.next(); inside the loop.. In order for the user to loggedin again..
do { // beginning of while - login
System.out.println("Insert student's surname followed by the first letter");
System.out.print("of their first name (e.g John Smith = smithj): ")
login = user_input.next(); // <--- you should ask for login here
...
updated:
//for the final if statement
if (loggedin) { //just use this boolean variable since you used it as an indicator if it is valid name or not
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
}
else {
System.out.println("poo");
}
actually, you don't need to put condition after the loop since you already filter it inside the loop so if the name is not valid it will not exit the loop until the user enter a valid name.. you can just do it like this after the loop
do{
..
}while(..)
System.out.println("Attend today: "+attendance[0]);
System.out.println("Grade: ");
I started from scratch, and have created this, which uses the same principles, but has solved my answer.
There are three users, each with their own login, password creation and password entry (if you have a better way to do this, please say).
package codeyom9a;
import java.util.Scanner;
public class Codeyom9a {
public static void main(String[] args) {
String[] names = {"Luke", "Jack", "Brad" };
String[] surnames = {"Mckeown", "Heard", "Reed" };
Scanner user_input = new Scanner(System.in);
boolean firstloggedin;
boolean passloggedin;
String firstlogin;
do { //login first name
firstloggedin = false;
System.out.print("Enter your first name: ");
firstlogin = user_input.next();
if (firstlogin.equals(names[0]) || firstlogin.equals(names[1]) || firstlogin.equals(names[2])) {
firstloggedin = true;
}
else {
System.out.println("Please try again.");
}
} while (! firstloggedin);
boolean secondloggedin;
String secondlogin;
do { //login surname
secondloggedin = false;
System.out.print("Enter your surname: ");
secondlogin = user_input.next();
if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])|| secondlogin.equals(surnames[1]) & firstlogin.equals(names[1]) || secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) {
secondloggedin = true;
}
else {
System.out.println("Please try again.");
}
} while (! secondloggedin);
if (secondlogin.equals(surnames[0]) & firstlogin.equals(names[0])) { //pass login user 1
String password1; //pass create user 1
System.out.print("Create a password (no spaces): ");
password1 = user_input.next();
boolean passloggedin1 = false;
do{
String passwordenter1; //pass enter user 1
System.out.print("Enter your password now: ");
passwordenter1 = user_input.next();
if (passwordenter1.equals(password1)) {
passloggedin1 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin1);
} //end user 1
if (secondlogin.equals(surnames[1]) & firstlogin.equals(names[1])) { //pass login user 2
String password2; //pass create user 2
System.out.print("Create a password (no spaces): ");
password2 = user_input.next();
boolean passloggedin2 = false;
do{
String passwordenter2; //pass enter user 2
System.out.print("Enter your password now: ");
passwordenter2 = user_input.next();
if (passwordenter2.equals(password2)) {
passloggedin2 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin2);
} //end user 2
if (secondlogin.equals(surnames[2]) & firstlogin.equals(names[2])) { //pass login user 3
String password3; //pass create user 3
System.out.print("Create a password (no spaces): ");
password3 = user_input.next();
boolean passloggedin3 = false;
do{
String passwordenter3; //pass enter user 3
System.out.print("Enter your password now: ");
passwordenter3 = user_input.next();
if (passwordenter3.equals(password3)) {
passloggedin3 = true;
System.out.println("Correct! You have now logged in.");
}
else {
System.out.println("Incorrect password!");
}
} while (! passloggedin3);
} //end user 3
}
}
If you type in "Luke", "Jack", or "Brad", it then requests for the surname (which is in the same index in the 'surnames' array). If both correct, it request for a password to be created, and then asks for the user to input that created password.
Regarding my first code, I don't know why this works and the other doesn't, any ideas why?

Validate user input against ArrayList

I am having issues with the following part of my code.
when "nn" is entered i get invalid code.
when valid code is entered i get invalid code however this only happens once.
program doesn't seem to work as intended. Please assist.
System.out.println("ENTER CODE (nn to Stop) : ");
ArrayList<Product> list = new ArrayList<Product>();
.
.
.
.
ArrayList<Code> codeList = new ArrayList<Code>();
for (Product product : list) {
System.out.print("CODE : ");
String pcode = scan.next();
if (pcode.equalsIgnoreCase("nn")) {
break;
}
if (!(code.equalsIgnoreCase(product.getCode()))) {
System.out.println("Invalid code, please enter valid code.");
System.out.print("CODE : ");
pcode = scan.next();
}
System.out.print("QUANTITY : ");
int quan = scan.nextInt();
while (quan > 20) {
System.out.println("Purchase of more than 20 items are not allowed, please enter lower amount.");
System.out.print("QUANTITY : ");
quan = scan.nextInt();
}
codeList.add(new Code(pcode, quan));
}
You want continue instead of break.
Also, you should only call code = scan.next() once inside the loop; otherwise you'll skip over some items.
String code = scan.next();
boolean match = false;
for (Product product : list) {
if (code.equalsIgnoreCase(product.getCode())) {
match = true;
break;
}
}
// now only if match is false do you have an invalid product code.
Update:
I still can't get this to work. What I am trying to do is test user
input to make sure that product code exists, if not prompt that the
product code entered is invalid and asks for correct code. I also need
to have the condition to stop order when "nn" is entered. I have tried
while loops, do-while loops etc. i can't seem to get it right. Please
assist. My problem is with writing code for multiple conditions. When
one is working correctly the other isn't.
while (true) {
final String code = scan.next();
if (isExitCode(code)) {
break;
}
if (!isValidCode(code)) {
System.out.println("Invalid code, please enter valid code.");
continue;
}
int quantity = -1;
while (true) {
quantity = scan.nextInt();
if (!isValidQuantity(quantity)) {
System.out.println("bad quantity");
continue;
}
break;
}
// if you've got here, you have a valid code and a valid
// quantity; deal with it as you see fit.
}
Now you just need to write the methods isExitCode(), isValidCode(), and isValidQuantity().

Categories