public static void addToUserList(User newUser){
boolean hasFound = false;
for (User user : users) {
if(user.getUserID() == newUser.getUserID()){
System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
hasFound = true;
break;
}
}
if(hasFound = false){
users.add(newUser);
}
}
How do I refactor this code? In users arraylist, there shouldn't be duplicate users by ID.
I think using boolean variable is a bit unnecessary but I couldn't find any better solution.
P.Ss: Also if there is a convenion for these kind of coding styles, can you provide a name? Thank you.
You don't need the boolean, just return from the method if the user exists.
public static void addToUserList(User newUser){
for (User user : users) {
if(user.getUserID() == newUser.getUserID()){
System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
return;
}
}
users.add(newUser);
}
please try with this.Change the == in first if to != like below and remove the last part
public static void addToUserList(User newUser){
boolean hasFound = false;
for (User user : users) {
if(user.getUserID() != newUser.getUserID()){
users.add(newUser);
}
else{
System.out.println("DUPLICATED USER ID: " + user.getUserID() + "ALREADY EXISTS");
}
}
}
Related
I have a login system that loops through all customers to see if a particular username and password match but it does not seem to work. The customers are all in an ObservableArrayList. I referred to this SO post to make it initially but it still did not work. Any help would be greatly appreciated. Thank you.
Other Info
TextField username,password;
Customer checkCustomer;
ObservableList<Customer> customers;
customers = FXCollections.observableArrayList();
Login System(GUI)
if(t.getSource() == logIn){
//Owner login
if(username.getText().equals("admin") && password.getText().equals("admin")){
System.out.println("success, owner logged in");
window.setScene(primaryOwner);
}
else {
if(findRegisteredCustomer(username.getText(),password.getText()) != null){
System.out.println("Success, customer logged in");
if(checkCustomer.getPoints() < 1000){
status = "Silver";
}
else if(checkCustomer.getPoints() > 1000){
status = "Gold";
}
welcome.setText("Welcome " + checkCustomer.getUsername() + ". " + "You have " + checkCustomer.getPoints() + " points. " + "Your status is " + status + ".");
System.out.println("success, " + checkCustomer.getUsername() + " has logged in");
window.setScene(customerStartScreen);
}
else {
System.out.println("Username: " + username.getText() + ", Password: " + password.getText());
System.out.println("failed, incorrect login details");
}
}
}
find if customer is registered method
public Customer findRegisteredCustomer(String username, String password){
for(Customer customerTest: customers){
if(customerTest.getUsername().equals(username) && customerTest.getPassword().equals(password)){
System.out.println("Registered user");
checkCustomer = customerTest;
return customerTest;
}
return null;
}
return null;
}
Customer class
public class Customer extends User {
private int points;
public Customer(String username, String password){
super(username,password);
points = 0;
}
public Customer(String username, String password, int points){
super(username,password);
this.points = points;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
You return null after your if block, remove the first return null in the findRegisterdCustomer method and you should be fine.
Also you might want to look into hashing, equals methods and default passwords and what the issues can be with those.
i am working on an android application registration page(in java language) where it contains 13 fields. i have done validation to all the fields and its working fine with toast messages. but my requirement is if any field raises a toast message then that field should be highlighted. here is my sample code
if (driverName.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter first name", Toast.LENGTH_LONG).show();
} else if (firname) {
Toast.makeText(ApplicationActivity.this, "please enter the first name correctly", Toast.LENGTH_LONG).show();
} else if (driverName_last.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter last name", Toast.LENGTH_LONG).show();
} else if (secname) {
Toast.makeText(ApplicationActivity.this, "please enter last name correctly", Toast.LENGTH_LONG).show();
} else if (fatherName.length() <= 0) {
Toast.makeText(ApplicationActivity.this, "Enter father name", Toast.LENGTH_LONG).show();
} else if (fathername) {
Toast.makeText(ApplicationActivity.this, "please enter father name correctly", Toast.LENGTH_LONG).show();
}
thanks in advance
You can use setError() method as follows instead of using Toast.
input.setError("Your particular error");
where, input is your EditText.
It will set the error to particular EditText when your if condition will be wrong or according to your given condition with the particular error message.
Its the better way than displaying Toast.
EDITED WITH CODE:
if (!Common.isValidLength(fName)) {
medFirstName.setError("Invalid First Name");
}
if (!Common.isValidLength(lName)) {
medLastName.setError("Invalid Last Name");
}
if (!Common.isValidEmail(email)) {
medEmailId.setError("Invalid Email");
}
if (!Common.isValidPassword(pass)) {
medPassword.setError("Invalid Password");
}
if (!Common.isValidPassword(confirmPassword)) {
medConfirmPassword.setError("Invalid Confirm Password");
}
if (!Common.isValidMatchPassword(pass, confirmPassword)) {
medConfirmPassword.setError("Password does not match");
}
For that create one Common class and put below methods in it :
/*
* A Common function to check internet connection.
* */
public static boolean isOnline(Context c) {
try {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
* A common function to check length for input.
* */
public static boolean isValidLength(String fName) {
if (fName.trim().length() > 0) {
return true;
}
return false;
}
/*
* A common function to validate Email id.
* */
public static boolean isValidEmail(String email) {
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
// validating password with retype password
public static boolean isValidPassword(String password) {
if (password != null) {
return true;
}
return false;
}
// validating of confirm password
public static boolean isValidMatchPassword(String pass, String confirmPassword) {
if (pass.equals(confirmPassword)) {
return true;
}
return false;
}
To hightlight field you have to set foucs for e.g.
firname.requestFocus();
Note: change firname with your edittext name.
requestFocus() method will return focus to view on which it is called.
for example
else if (firname) {
Toast.makeText(ApplicationActivity.this, "please enter the first name correctly", Toast.LENGTH_LONG).show();
firname.requestFoucs(); ****// here firname is edittext****
}
I would like to know how to send a player a list of their shops when they type /shoplist. Also, I would like to know how to change the name of a shop depending on what they type so if they use /shopname Shop1 Pie it would change the name of Shop1 to pie. Or if they do not have a shop called shop1 then it would say a message if they don't have any shops when they make a shop then it builds a new section in the config for them.
Here is my main file:
public class Shops extends JavaPlugin implements Listener {
public void onEnable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Enabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getPluginManager().registerEvents(new Signs(), this);
getConfig().options().copyDefaults(true);
saveConfig();
}
public void onDisable() {
Bukkit.getServer().getLogger().info("************************");
Bukkit.getServer().getLogger().info("*Shops Plugin Disabled *");
Bukkit.getServer().getLogger().info("*Shops by McMatt *");
Bukkit.getServer().getLogger().info("************************");
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shops")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You must be a player to run this command");
return true;
}
Player player = (Player) sender;
if (!player.hasPermission("shops.shops")) {
player.sendMessage(ChatColor.RED + "You do not have to permission (shops.shops)");
return true;
} else {
player.sendMessage(ChatColor.GOLD + "Shops:");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Commands" + ChatColor.RED + "---");
player.sendMessage(ChatColor.DARK_GREEN + "/shops" + ChatColor.GREEN + " Displays this");
player.sendMessage(ChatColor.DARK_GREEN + "/shopslist" + ChatColor.GREEN + " Used to list shops");
player.sendMessage(ChatColor.RED + "---" + ChatColor.GOLD + "Signs" + "---");
player.sendMessage(ChatColor.DARK_GREEN + "First line:" + ChatColor.GREEN + " [shop]");
player.sendMessage(ChatColor.DARK_GREEN + "Second line:" + ChatColor.GREEN + " {Open or Closed}");
}
}
return true;
}
public boolean onCommand1(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (cmd.getName().equalsIgnoreCase("shopslist")) {
sender.sendMessage("Getting shops info!");
sender.sendMessage(getConfig().getString("" + sender.getName()));
return true;
}
return false;
}
}
Here's my listener file
public class Signs implements Listener {
#EventHandler
public void onSignChange(SignChangeEvent e) {
if (e.getLine(0).equalsIgnoreCase("[shop]")) {
Block attached = e.getBlock().getRelative(0, -1, 0);
String name = e.getPlayer().getDisplayName();
if (!(attached.getType() == Material.CHEST))
e.getPlayer().sendMessage(ChatColor.RED + "Please place the shop on a chest!");
else {
if (!e.getPlayer().hasPermission("shops.create"))
e.getPlayer().sendMessage(ChatColor.RED + "You don't have permission to create a shop! (shops.create)");
else {
if (!Arrays.asList("open", "closed").contains(e.getLine(1).toLowerCase())) {
e.getPlayer().sendMessage(ChatColor.RED + "You must specify if the shop is open or closed on the second line!");
} else {
boolean closed = true;
if ("open".equalsIgnoreCase(e.getLine(1))) {
closed = false;
}
String lineThree = closed ? "§cClosed" : "§aOpen";
e.setLine(3, lineThree);
e.setLine(0, "§9[Shop]");
e.setLine(1, "§b" + name + "'s");
e.setLine(2, "§bShop");
e.getPlayer().sendMessage(ChatColor.GREEN + "Shop Created!");
e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.LEVEL_UP, 10, 10);
//if(getConfig().equals(null)){
//int shopAmount = 0;
//shopAmount = shopAmount + 1;
//getConfig().createSection(name);
//getConfig().addDefault(name + ":.Shops:", "Shop" + shopAmount);
}
}
}
}
}
#EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
Player p = e.getPlayer();
Block b = e.getClickedBlock();
Material m = b.getType();
if (!(m == Material.SIGN_POST)) {
return;
} else {
Sign sign = (Sign) e.getClickedBlock().getState();
if ((sign.getLine(0).equalsIgnoreCase("§9[Shop]"))) {
if ((sign.getLine(3).equalsIgnoreCase("§aOpen"))) {
p.sendMessage("I opened the shop!");
}
}
}
}
}
}
And here's my configuration file
McMatt:
- Shop1
You could get the List<String> of all of the player's shops by using
config.getStringList(playerName);
So, for example, if your config looked like this:
McMatt:
- "Shop1"
- "Awesome Shop"
jojodmo:
- "Jojo Shop"
using
config.getStringList("McMatt");
Would return a List<String> containing the strings Shop1 and Awesome Shop.
Also, to avoid a NullPointerException, you should make sure the player has shops in the config by using
if(config.contains(playerName))
and send the player a message telling them that they have no shops.
So, your code could look something like this:
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
if(cmd.getName().equalsIgnoreCase("shops")){
//your code
if(sender instanceof Player){
Player player = (Player) sender;
String name = player.getName();
if(config.contains(name)){
List<String> shops = config.getStringList(name);
for(String shop : shops){
//do something with the shop
}
}
else{
//the user has no shops
}
}
//...
}
}
public void compare(ArrayList list_old, ArrayList list_new) {
try {
Iterator<User> iterator_old = list_old.iterator();
Iterator<User> iterator_new = list_new.iterator();
//Check New User Is Added
while (iterator_new.hasNext()) {
Log.i("Test", "inside!");
User user_new = iterator_new.next();
boolean NEW = true;
while (iterator_old.hasNext() && NEW) {
User user_old = iterator_old.next();
if (user_new.getUsername().equals(user_old.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_new.getUsername() + " has been added.");
}
}
//Check User Is Removed
while (iterator_old.hasNext()) {
Log.i("Test", "inside");
User user_old = iterator_old.next();
boolean NEW = true;
while (iterator_new.hasNext() && NEW) {
User user_new = iterator_new.next();
if (user_old.getUsername().equals(user_new.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_old.getUsername() + " has been removed.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
In this function I am comparing my old list with my new list.
The first while loop check, is any new user added and second while loop check, is any user is removed.
When I am running this application only my first while loop execute and it does not execute second while loop.
I checked with Log.i("Test", "inside!"); and I found it does not come inside my second while loop.
Please help
You need to re-initialize the iterator,
public void compare(ArrayList list_old, ArrayList list_new) {
try {
Iterator<User> iterator_old;
Iterator<User> iterator_new = list_new.iterator();
//Check New User Is Added
while (iterator_new.hasNext()) {
Log.i("Test", "inside!");
User user_new = iterator_new.next();
boolean NEW = true;
iterator_old = list_old.iterator();
while (iterator_old.hasNext() && NEW) {
User user_old = iterator_old.next();
if (user_new.getUsername().equals(user_old.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_new.getUsername() + " has been added.");
}
}
//initialize again
iterator_old = list_old.iterator();
//Check User Is Removed
while (iterator_old.hasNext()) {
Log.i("Test", "inside");
User user_old = iterator_old.next();
boolean NEW = true;
iterator_new = list_new.iterator();
while (iterator_new.hasNext() && NEW) {
User user_new = iterator_new.next();
if (user_old.getUsername().equals(user_new.getUsername())) {
NEW = false;
}
}
if (NEW) {
generateNotification(getApplicationContext(), user_old.getUsername() + " has been removed.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
You're not resetting your iterators anywhere, so I don't think any of that code is working as you want it to. Your code would probably work and be much more readable if you used a for-each loop, which all Iterable classes support. This will avoid the need to create and reset iterators entirely.
for (User newUser : list_new) {
for (User oldUser : list_old)
// Compare
}
for (User oldUser : list_old) {
for (User newUser : list_new)
// Compare
}
I have an assignment to carry out using BlueJ where I am given a class called HW4CustomerList and I must create a Text-Based UI for it. The class I have to create is called CustomerTUI and contains a method called addCustomer which adds a new Customer object of mine to an ArrayList. This method in particular is what I am stuck with. The class specification says that I cannot take any parameters (i.e. a no-args method). In previous work we have used the BlueJ 'method box' to interact with objects and add them to ArrayLists, however I do not know if this can be used in this particular instance. Please find below my code so far for CustomerTUI and the code for the Customer class and HW4CustomerList class. Many thanks in advance.
CustomerTUI class:
import java.util.Scanner;
public class CustomerTUI
{
private HW4CustomerList customerList;
private Scanner myScanner;
public CustomerTUI()
{
customerList = new HW4CustomerList();
myScanner = new Scanner(System.in);
}
public void menu()
{
int command;
boolean running = true;
while(running)
{
displayMenu();
command = getCommand();
execute(command);
}
}
private void addCustomer()
{
customerList.addCustomer();
}
private void displayMenu()
{
System.out.println(" CustomerList program ");
System.out.println("=========================================");
System.out.println("|Add a customer to the list..........[1]|");
System.out.println("|Get number of customers.............[2]|");
System.out.println("|Remove a customer from the list.....[3]|");
System.out.println("|Show all customer details...........[4]|");
System.out.println("|Show a specific customers details...[5]|");
System.out.println("|Quit................................[6]|");
System.out.println("=========================================");
}
private void execute(int command)
{
if(command == 1)
{
addCustomer();
}
else if(command == 2)
{
getNumberOfCustomers();
}
else if(command == 3)
{
removeCustomer();
}
else if(command == 4)
{
showAllCustomers();
}
else if(command == 5)
{
showCustomer();
}
else if(command == 6)
{
quitCommand();
}
else
{
unknownCommand(command);
}
}
private int getCommand()
{
System.out.println("Enter the command of the function you wish to use: ");
int command = myScanner.nextInt();
return command;
}
private void getNumberOfCustomers()
{
if(customerList.getNumberOfCustomers() == 1)
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customer.");
}
else
{
System.out.println("We have " + customerList.getNumberOfCustomers() + " customers.");
}
}
private void quitCommand()
{
System.out.println("The program is now closing down...");
System.exit(0);
}
private void removeCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to remove: ");
accNo = myScanner.next();
if (customerList.removeCustomer(accNo) == true)
{
System.out.println("Customer with account number " + accNo + " was successfully removed.");
}
else
{
System.out.println("Customer with account number " + accNo + " was NOT successfully removed.");
System.out.println("Please try again.");
}
}
private void showAllCustomers()
{
customerList.getAllCustomers();
}
private void showCustomer()
{
String accNo;
System.out.println("Enter the account number of the customer you wish to view: ");
accNo = myScanner.next();
if(customerList.getCustomer(accNo) == false)
{
System.out.println("Could not find customer with account number " + accNo + ".");
}
else
{
return;
}
}
private void unknownCommand(int command)
{
System.out.println("Command number " + command + " is not valid. Please try again.");
}
}
HW4CustomerList class:
import java.util.*;
public class HW4CustomerList
{
private ArrayList<Customer> customers;
public HW4CustomerList()
{
customers = new ArrayList<Customer>();
}
public void addCustomer(Customer customer)
{
customers.add(customer);
}
public int getNumberOfCustomers()
{
return customers.size();
}
public boolean getCustomer(String accountNumber)
{
for(Customer customer : customers)
{
if(accountNumber.equals(customer.getAccountNumber()))
{
customer.printCustomerDetails();
return true;
}
}
return false;
}
public void getAllCustomers()
{
for(Customer customer : customers)
{
customer.printCustomerDetails();
System.out.println("\n");
}
}
public boolean removeCustomer(String accountNumber)
{
int index = 0;
for (Customer customer: customers)
{
if (accountNumber.equals(customer.getAccountNumber()))
{
customers.remove(index);
return true;
}
index++;
}
return false;
}
}
I think all you need to do is create a new Customer object in your addCustomer() method. This would probably require getting additional details:
public void addCustomer()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter customer name: ");
String name = scanner.nextLine();
//any additional details
Customer customer = new Customer(name, otherParams);
customers.add(customer);
}
Hope that helps!