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());
}
}
Related
I am trying to make some code that should keep track of a win/loss ratio. I have a for loop that checks if a name is present in a separate variable, this works but when I try to do it again it stalls.
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
After the code it should go back to a while loop, but it just stalls instead. If I comment out the name 2 part, the code works, but I need both parts.
Edit 1:
Heres the whole code
public class Counter {
#SuppressWarnings("resource")
public static void main(String[] args) {
int intTemp;
String stringTemp;
int keepGoing = 1;
int numPlayers = 0;
Player[] players = new Player[999];
Scanner scan = new Scanner(System.in);
System.out.println("Melee Score Tracker");
while (keepGoing == 1) {
System.out.println("\nPrint Scores\t1\nNew Match\t2\nNew Player\t3\nExit\t\t4");
intTemp = scan.nextInt();
// Print Scores
if (intTemp == 1) {
intTemp = 0;
System.out.print("\n");
for (int i = 0; i < numPlayers; i++) {
players[i].print();
}
}
// New Match
if (intTemp == 2) {
intTemp = 0;
System.out.println("\nEnter Name 1");
scan.nextLine();
String name1 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name1.equals(players[i].name)) {
players[i].win++;
break;
}
}
System.out.println("\nEnter Name 2");
scan.nextLine();
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
}
// New Player
if (intTemp == 3) {
intTemp = 0;
System.out.println("\nWhat's the player's name?");
scan.nextLine();
stringTemp = scan.nextLine();
players[numPlayers] = new Player();
players[numPlayers].name = stringTemp;
numPlayers++;
System.out.println(numPlayers);
}
// Exit
if (intTemp == 4) {
System.exit(0);
}
}
}
}
It stalls because of this;
scan.nextLine();
scan.nextLine();
String name2 = scan.nextLine();
It is waiting for input 3 times. You only want input once so replace it with;
String name2 = scan.nextLine();
In the future things like this can easily be debugged by checking if the code actually enters the for loop by printing out a little message in the loop.
String name2 = scan.nextLine();
for (int i = 0; i < numPlayers; i++) {
System.out.println("We have entered the loop.");
if (name2.equals(players[i].name)) {
players[i].loss++;
break;
}
}
If you see output in the console then you know the problem is not with the loop itself, but is before it.
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);
}
}
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 want to add a loop to my program so that when a user enters an incorrect name it goes back to the start of the program and asks them to enter their name again. I think I need a do-while loop but I am not sure how to implement it with the if statements and boolean already included. I want the user to be only have three entries and if they get it wrong three times then the program closes.
import java.util.Scanner;
public class Username
{
public static void main(String[] args)
{
{
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++)
{
if (name[i].equals(name1))
{
System.out.println("you are verified you may use the lift");
b = false;
break;// to stop loop checking names
}
}
if (b)
{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
You can use a condition in the while loop. Something along the lines of:
boolean b = false;
while(!b){
System.out.println("Enter your name");
String name1 = kb.nextLine();
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
b = true;
System.out.println("you are verified you may use the lift");
}else{
System.out.println("Invalid entry 2 attempts remaining, try again");
}
}
}
The loop will quit if the name condition is fulfilled and will loop around if it is not.
You can do it like this:
int count = 0;
point:
do {
System.out.println("Enter your name");
String name1 = kb.nextLine();
boolean b = true;
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift");
b = false;
break point;// to stop loop checking names
}
}
if (b) {
count++;
System.out.println("Invalid entry 2 attempts remaining, try again");
}
while(!b || count <=3)
Use the following approach. Good thing is that it is a clean and robust solution.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class AccessPoint
{
private Scanner scanner;
private List<String> usernames;
public AccessPoint()
{
scanner = new Scanner(System.in);
usernames = Arrays.asList("Barry", "Matty", "Olly", "Joey");
if (tryAccessForTimes(3))
{
allowAccess();
}
else
{
denyAccess();
}
scanner.close();
}
public static void main(String[] args)
{
new AccessPoint();
}
private boolean tryAccessForTimes(int times)
{
boolean accessAllowed = false;
for (int tryIndex = 1; tryIndex <= times && !accessAllowed; tryIndex++)
{
String userInput = getUserName();
for (String userName : usernames)
{
if (userName.equals(userInput))
{
accessAllowed = true;
break;
}
}
if (!accessAllowed)
{
printNumberOfTriesLeft(times, tryIndex);
}
}
return accessAllowed;
}
private void printNumberOfTriesLeft(int times, int tryIndex)
{
int triesLeft = times - tryIndex;
if (triesLeft != 0)
{
System.out.println("You have " + triesLeft
+ (triesLeft == 1 ? " try" : " tries") + " left.");
}
}
private String getUserName()
{
System.out.print("Enter Username: ");
return scanner.nextLine();
}
private void allowAccess()
{
System.out.println("Access Granted. Allowed to use lift.");
}
private void denyAccess()
{
System.out.println("Access Denied.");
}
}
package com.loknath.lab;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class User1 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"zerr", "barry", "matty", "olly", "joey" }; // elements
String []temp=name;
Arrays.sort(temp);
while (true) {
System.out.println("Enter your name");
String name1 = kb.nextLine();
if (Arrays.binarySearch(temp,name1)>=0) {
System.out.println("you are verified you may use the lift");
break;
} else {
System.out.println("Not a verified user try again!");
}
}
System.out.println("Done");
}
}
output
Enter your name
loknath
Not a verified user try again!
Enter your name
chiku
Not a verified user try again!
Enter your name
zerr
you are verified you may use the lift
Done