Can someone help me with my code please. Im a begginer and this thing called java really confusses me :) my problem is that i have to remove user/s, but my ouput is allways just user name not found... thanks in advance
public void removeUser() {
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
if (checks == 1) {
for (int i = 0; i < userList().size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
userName = input.next();
if (userList.equals(userName)) {
userList.get(i);
userList.remove(userName);
System.out.println("You succesfully removed user acount");
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
} else {
System.out.println("User name not found");
}
}
}
if (checks == 0) {
administrator();
}
}
why do you think that this would work?
if (userList.equals(userName))
??
Maybe just try removing it
boolean removed = userList.remove(userName);
if (removed) {
System.out.println("You succesfully removed user acount");
}
No looping required
see
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(java.lang.Object)
So your code could look like
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
while (checks == 1) {
System.out.println("Input user name for the account you want to be deleted");
userName = input.next();
if (userList.remove(userName)) {
System.out.println("You succesfully removed user acount");
}
else {
System.out.println("User name not found");
}
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
}
First thing that here you do with your code is change theif (checks == 1) to while loop while(checks == 1), because if can be executed only one time.
Second thing if (userList.equals(userName)) is never true, thus the if clause won't be executed. You first get the user name from the list like this String name userList.get(i); then now you can check if it is equal like this
if(name.equals(userName)) //or userList.contains(userName){
// userList.remove(userName);
// OR
// userList.remove(i);
}
Eidt:
You can change your code as below, maybe work for you
List<String> userList = new ArrayList<>();
userList.add("AA");
userList.add("BB");
userList.add("CC");
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
while (checks == 1) {
for (int i = 0; i < userList.size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
String userName = input.next();
if(userList.remove(userName)) {
System.out.println("You scornfully removed user account");
} else {
System.out.println("User name not found");
}
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
}
}
if (checks == 0) {
administrator();
}
public static void main(String[] args) {
List<String> customerNames = new ArrayList<String>();
customerNames.add("john");
customerNames.add("lily");
customerNames.add("druid");
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter 1 ");
if(input.nextInt() != 1){
System.out.println("break checks ... ...");
return;
}
for(int i = 0; i < customerNames.size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
if (customerNames.get(i).equals(input.next())) {
customerNames.remove(i);
System.out.println("You succesfully removed user acount");
System.out.println("If you want to exit press 0 ... ...\n");
if(input.nextInt() == 0){ //break
break;
}
} else {
System.out.println("User name not found... ...\n");
}
}
}
public static void main(String[] args) {
List<String> customerNames = new ArrayList<String>();
customerNames.add("john");
customerNames.add("lily");
customerNames.add("druid");
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter 1: ");
if(input.nextInt() != 1){
System.out.println("break checks ... ...");
return;
}
System.out.println("========= start =========");
System.out.println("Please enter 1: ");
while(input.nextInt() != 0){
System.out.println("Input user name for the account you want to be deleted... ...");
System.out.println("enter name:");
String _name = input.next();
for(int i = 0; i < customerNames.size(); i++) {
if(_name.equals(customerNames.get(i))){
customerNames.remove(_name);
System.out.println("You succesfully removed user acount");
break;
}
}
System.out.println("If you want to exit press 0 ... ...\n");
System.out.println("input numeric:");
}
System.out.println("========= end =========");
//break
if(customerNames.size() == 0){return;}
for(String name : customerNames){//print names
System.out.println(name);
}
}
Related
How do I get the code below to repeat the command, where the players name already exists in the key set?
public static Map<String, Player> players = new TreeMap<>();
for (int loop = 1; loop <= 4; loop++) {
System.out.println("enter player"+loop+"s name");
name = scanner.next();
if(players.keySet().contains(name)) {
System.out.println("name in use - enter new name");
}else {
players.put(name, new Player());
}
}
You can use a variable (e.g. boolean alreadyExists as shown in the code below) to track a valid input and loop back in case of invlid input.
boolean alreadyExists;
for (int loop = 1; loop <= 4; loop++) {
do {
alreadyExists = false;
System.out.println("enter player" + loop + "s name");
name = scanner.next();
if (players.keySet().contains(name)) {
System.out.println("name in use - enter new name");
alreadyExists = true;
} else {
players.put(name, new Player());
}
} while (alreadyExists);
}
I suppose you need a limited number of valid players.
while (players.size() < 4) {
name = scanner.next();
if(players.keySet().contains(name)) {
System.out.println("name in use - enter new name");
} else {
players.put(name, new Player());
}
}
This should be a program to take in a password from the user and check it against various parameters.
I've an issue with the do while loop, it prints:
Please enter your password.
Error. Password is too short. Try again.
Then it prints this after selecting option
1. Enter your own password for verification
The program should allow the user to enter a password before printing any error messages.
First time using this site. Any help with this would be greatly appreciated.
import java.security.SecureRandom;
import java.util.*;
public class CC_CA2
{
// Main Method
public static void main(String[] args)
{
Scanner keyboardIn = new Scanner(System.in); //Create Scanner object
String[] data = {"123456","password","12345","12345678","qwerty","123456789","1234","baseball","dragon","football","1234567","monkey","letmein","abc123","111111","mustang","access","shadow","master","michael"};
String correct;
int numLetterCheck = 0;
int option;
boolean found = false;
boolean check;
boolean digitFound = false;
boolean letterFound = false;
//Menu
System.out.println("Welcome to the password checker.");
System.out.println("Would you like to:");
System.out.println("1. Enter your own password for verification.");
System.out.println("2. Have an easy to remember random password generated for you.");
option = keyboardIn.nextInt();
if (option==1)
{
do
{
check = true;
found=false;
System.out.println("Please enter your password."); // get user password
correct = keyboardIn.nextLine();
if (correct.length()<8) // 1. check password > 8 characters
{
System.out.println("Error. Password is too short. Try again.");
check=false;
continue;
}
if (correct.contains(" ")) //2. check if password contains any spaces
{
System.out.println("Error. Password contains a space. Try again.");
check=false;
continue;
}
for(int i = 0; i < data.length; i++) // 3. check common passwords
{
if(data[i].equals(correct)) //if match found
{
found = true; //remember that it is found
}
}
if(found) //if found is true
{
System.out.println("Error. This is a common password. Try again.");
check=false;
continue;
}
for (char ch : correct.toCharArray()) // 4. Make sure password contains at least one letter and one number
{
if (Character.isDigit(ch))
{
digitFound = true;
}
if (Character.isLetter(ch))
{
letterFound = true;
}
if (digitFound && letterFound)
{
numLetterCheck = 0;
}
else
{
numLetterCheck = 1;
}
}
while (numLetterCheck == 1)
{
letterFound=false;
digitFound=false;
System.out.println("Error. Password must contain at least one letter and one number. Try again.");
correct = keyboardIn.nextLine();
}
}while(check == false);
}
}}
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
}
}
You should refactor to separate the loop for finding/not finding the ball (or not), and do whatever you need to do with the ball (or error if not found) OUTSIDE the loop. This helps with readability because more of your lines are less indented, and it helps communicate your intent because most of your code in the loop is only going to be executed once anyway.
int ballIndex = -1;
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
ballIndex = nameBallArray[i];
break;
}
}
if (ballIndex >= 0) {
// found - do everything using ballIndex
} else {
// not found - display error
}
Set a flag variable to 0 before loop. Inside if set it 1. After the loop check if it is still zero. then print appropriate message that no item found.
Boolean flag = false; // before loop
flag = true; //inside if
// After loop
if(!flag)
System.out.println("Not Found");
Try this:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
return;
}
}
System.out.println("ball not found");
}
You could create a boolean and set it to true in your if statement that means it's been found. You could check the boolean after loop to see if it's true or false then display error message if true.
Example:
public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) {
boolean found = false; //boolean for if it's found or not
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the name of the ball you would like to modify: ");
String name = keyboard.nextLine();
for (int i = 0; i < count; i++) {
if (name.compareToIgnoreCase(nameBallArray[i]) == 0) {
found = true; //set boolean if found
System.out.println("Please enter a new name for the ball: ");
String ballName = keyboard.nextLine();
System.out.println("Please enter a new weight for the ball: ");
int ballWeight = keyboard.nextInt();
System.out.println("Please enter a new hook potential for the ball: ");
String hookPotential = keyboard.next();
nameBallArray[i] = ballName;
ballWeightArray[i] = ballWeight;
hookPotentialArray[i] = hookPotential;
System.out.println("The ball list has been updated.");
System.out.println("");
break; //break out of loop if item found
}
}
//check if boolean is false then print error message
if (!found)
{
System.out.println("There was a problem finding your item.");
}
I also added a break at end of if statement to break out of the loop if the item was found(no point in continuing on if the item was already found).
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.
I've set up a "menu" that prints to console. Takes user input, calls according method, and then should return to the menu for further instruction. How should I structure my code so that it outputs the "menu" after it's done doing whatever it's doing?
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
EntryNode n = new EntryNode();
AddressList addressBook = new AddressList();
String menu = " ";
System.out.println("******************************************************************");
System.out.println("Welcome to the Jackie 2000 Address Book");
System.out.println("What do you want to do? ");
System.out.println("[p] View All Entries in Address Book [a] Add New Entry");
System.out.println("[d] Remove An Entry [s] Search for Entry");
System.out.println("[i] Import Address Book [x] Export Address Book");
System.out.println("[z] Exit");
System.out.println();
System.out.println("Please enter your choice: ");
menu = keyboard.next().toLowerCase();
if (menu.equals("p")) {
try {
addressBook.printList();
}
catch (Exception e){
}
}
else if (menu.equals("a")) {
System.out.println("Enter in the first name ");
String firstName = keyboard.next().toUpperCase();
System.out.println("Enter in the last name ");
String lastName = keyboard.next().toUpperCase();
System.out.println("Enter in the phone number");
String phoneNum = keyboard.next().toUpperCase();
System.out.println("Enter in the email");
String email = keyboard.next().toUpperCase();
addressBook.addEntry(firstName,lastName,phoneNum,email);
}
else if (menu.equals("d")) {
EntryNode temp = head;
for (int i = 0; i <addressBook.length(); i++) {
System.out.println(i + " Name: " + temp.getFirstName() + " " + temp.getLastName() + " "
+ temp.getPhoneNum() + " " + temp.getEmail());
temp = temp.getNext();
}
System.out.println(" ");
System.out.println("Please enter the index of the entry you wish to delete ");
int index = keyboard.nextInt();
addressBook.removeEntry(index);
}
else if (menu.equals("s")) {
System.out.println("Do you want to search by email or name? ");
String decision = keyboard.next();
if (decision.equals("email")) {
System.out.println("What email address are you looking for? ");
String email = keyboard.next();
addressBook.searchEmail(email);
}
else if (decision.equals("name")) {
System.out.println("What name are you looking for?");
String name = keyboard.next();
addressBook.searchEntry(name);
}
else System.out.println("Invalid entry. Type in 'email' or 'name'");
}
else if (menu.equals("i")) {
addressBook.importBook();
}
else if (menu.equals("x")) {
addressBook.exportBook();
}
else if (menu.equals("e")) {
System.exit(0);
}
else {
System.out.println("Invalid Entry");
}
}
}
You should definitely take a look at java's switch statement: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You could have the entire switch-case statement inside a while loop with a boolean for when it should exit. For example:
while(!exit){
switch(input){
case "a": do something;break;
case "d":...
...
case "e": exit = true;
}
}
If you want the same menu to be displayed again after the user entered a choice and the program executed what he had to do, just put the whole process in a while or do...while loop and only exit it when the user choose the exit option.
Put a menu printlns into a separate static method. Call it after each addressBook method call, just before you close else if, except for an exit case.