Allow user to input unique values - java

I'm trying to get input from the user to select players from an ArrayList. All the players in the ArrayList have a unique ID the user selects 5 - 8 players to start the program but I do not want to allow the user to input the same ID again as it will have a duplicate.
Heres what I m trying to do
I still am not getting this I tried this
public void SelectAthlete(){
Data ath = new Data();
ath.athleteData();
boolean choice = true;
int p=0;
String id;
int value =0;
Scanner input = new Scanner(System.in);
System.out.println();
do{
System.out.println();
System.out.print("\tEnter the number of Participants you want to Compete: ");
p=input.nextInt();
System.out.println("\tYou have Decided to compete with" +" " + p + " " +"Athletes");
if(p>=5 && p<=8){
System.out.println("\tEnter the Athlete ID : ");
for (int i=0;i<p;i++){
value=0;
id = input.next();
if(id.substring(0,1).equals("R") || id.substring(0,1).equals("P")){
for(int k=0;i<Data.AthleteData.size();k++)
{
if(Data.AthleteData.get(k).getID().contains(id))
{
value++;
choice = Data.Inputlist.add(id);
}
else if (!choice)
{
value--;
System.out.println("Please Enter Unique Value");
input.nextLine();
}
for(int j = 0; j<Data.AthleteData.size();j++)
{
if(id.equals(Data.AthleteData.get(j).getID()))
{
value++;
}
}
}
}
if(value!=0)
{
Data.Inputlist.add(id);
}
else
{
System.out.println("Enter a valid ID (in UPPER Case)");
input.nextLine();
i--;
}
}
choice = false;
}
else{
System.out.println("\n\tHowever You need to have
atleast 5 Athletes or atmost 8 Athletes to Start a game.");
input.nextLine();
}
for (int m=0;m<Data.AthleteData.size();m++){
if (Data.Inputlist.contains(Data.AthleteData.get(m).getID()))
{
System.out.println(Data.AthleteData.get(m));
}
}
}while(choice);

You could use a HashSet and see the response of the add method as follows:
Set<String> someSet = new HashSet<String>();
boolean isUnique = someSet.add("abc");
System.out.println(isUnique); // this will output true as abc does not already exist in the set and add operation was successful
isUnique = someSet.add("abc");
System.out.println(isUnique); //this will output false as abc already exists in the set and hence cannot be added again
But since you are using a Custom Object and not a String, you will need to declare the set as follows:
Set<YourClass> someSet = new HashSet<YourClass>();
In addition to that you will need to make sure that the equals method in YourObject class is implemented correctly too.
You can refer to these links for more information about equals: http://www.geeksforgeeks.org/overriding-equals-method-in-java/
and
https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/

There are many ways you can do this.
1.) After taking number you can loop back to check if it exist in the Arraylist.(NOT RECOMMENDED) as it have high runtime complexity.
2.) Simply you can use contains() method of arraylist to check if it is present already.
3) You can use a bitset for number and set it true when ever they are assigned.Later you can compare it with the bool value to check if it set or not. see https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html for more info on bitset

Related

Stop duplicate input (scanner & arrays)

I'm fairly new at programming. Currently im working on a uni project to create a basic text game using java. The problem im having is trying to figure out how to implement a business rule that does not allow a user to enter the same name. I have it set up so the scanner reads into the array. I'm using Java and this is my first time using the forum so i greatly appreciate any help given and thank all of you in advance!:)
And apologies for the poor formatting i dont know how to post properly yet.
try {
// Takes in the number of players
int noOfPlayers;
Scanner s = new Scanner(System.in);
System.out.println("Enter number of players between 2 and 4");
noOfPlayers = s.nextInt();
s.nextLine();
if (noOfPlayers < 2 || noOfPlayers >= 5) { // limits number of players enter no less than 2 and no greater than 4
System.out.println("Nope wrong number");
enterInfo();
s.close();
return;
} else {
// array for storing player names
String[] names = new String[noOfPlayers];
// iterates through the array depending how many players are selected
// and takes in String input
for (int counter = 0; counter < noOfPlayers; counter++) {
System.out.println("Enter name of player : " + (counter + 1));
names[counter] = s.nextLine();
// fix this to stop same name sbeing entered
//if(names.equals(names)) {
// System.out.println("Enter a different name");
// counter--;
// }
}
}
s.close();
} catch (Exception e) {
System.out.println("Problem");
}
}
How about use Set? Set has to have all different things.
Like in Array [kim,lee,kim,park] but in Set [kim,lee,park]
input kim => Array [kim] set[kim] lenth 1 == size 1
input lee => Array [kim,lee] set[kim,lee] lenth 2 == size 2
input kim => Array [kim,lee,kim] set[kim,lee] lenth 3 != size 2
then all you have to do is tell them "make another name plz"
String name = s.nextLine();
names[counter] = name;
Set<String> set = new HashSet<String>();
set.add(name)
if(names.length != set.size())
{
System.out.println("Enter a different name");
counter--;
}
I hope you understand my poor explanation.

What loop should I use? [duplicate]

This question already has answers here:
when to use while loop rather than for loop
(14 answers)
Closed 1 year ago.
I am supposed to do a word-quiz game between two languages in Java, and I am not sure what type of loop should be used when controlling the input from the user! I have three "conditions/terms"
if the user types the right answer
if the user has some spelling mistake
if the user types q to quit the game
I was first thinking of using a for loop, but I don't seem to figure it out!
My code looks like this right now
public static int takeTest(ArrayList<Sweng> Wordlist) {
int result = 0;
Scanner keyboardInput = new Scanner(System.in);
for (int i = 0; i < Wordlist.size(); i++) {
System.out.println(Wordlist.get(i).getSweWord());
String answer = keyboardInput.nextLine();
}
//...
}
If you don't know how many times the loop need to be executed, you can use a do-while loop.
This loop first execute the code inside the do brackets, and then check the condition.
This is an implementation example:
Scanner s = new Scanner(System.in);
String input; // a variable to store the input
do {
System.out.println(/*your question here*/);
input = s.nextLine();
// do something
} while(!input.equals("q")); // exit the loop if 'input' equals "q"
Otherwise, you can do something like that, but it's a very bad and rough way to do this. I don't recommend you to use it.
Note: You'll need to adjust this code with your ArrayList<Sweng> WordList. It's just an example!
ArrayList<String> questions = new ArrayList<String>();
ArrayList<ArrayList<String>> possibleAnswers = new ArrayList<ArrayList<String>>(); // list of a list because we need a set of strings for every questions
ArrayList<String> correctAnswers = new ArrayList<String>();
// init the lists
Scanner s = new Scanner(System.in);
int result = 0;
boolean quit = false; // if true, then quit the for loop
for(int i = 0; i < questions.size(); i++) { // repeat 'questions.size()' times
String answer = null;
do {
if(answer != null) System.out.println("This isn't a valid answer!"); // if 'answer' is null, don't show this output because it's the first time in the loop
System.out.println(questions.get(i));
answer = s.nextLine();
if(answer.equals("q")) { // if input is "q", set 'quit' to 'true' and break the do-while loop
quit = true;
break;
}
} while(!possibleAnswers.get(i).contains(answer)); // if the answer is a valid answer, quit the loop
if(quit) break; // if quit is true, break the for loop
if(answer.equals(correctAnswers.get(i))) { // check for correct answer
System.out.println("Correct!");
result++;
} else System.out.println("Wrong!");
}
System.out.println("You scored " + result + "!");
Since you actually know how often you want to loop at max (max. the amount of questions inside your wordList, since it's a quiz), you can actually keep the for loop.
You could use a while or do-while loop here, but then you would need a seperate index variable to keep track of the current question, and this fact alone indicates that a for loop is more suitable here.
I modified your code snippet to change / add the following things:
Variable names should start lowercase. So Wordlist -> wordList.
Added conditions regarding verification of the answer and quitting.
Added some print statements.
Example:
public static int takeTest(ArrayList<Sweng> wordList) {
int result = 0;
Scanner keyboardInput = new Scanner(System.in);
for (int i = 0; i < wordList.size(); i++) {
System.out.println(wordList.get(i).getSweWord());
System.out.println("Please enter the answer:");
String answer = keyboardInput.nextLine();
if (wordList.get(i).getResultWord().equals(answer)) { // correct answer
System.out.println("Correct answer!");
result++;
} else if ("q".equals(answer)) { // quitting
System.out.println("Thank you for playing!");
break;
} else { // incorrect answer
System.out.println("Incorrect answer!");
}
}
return result;
}
Sidenote: Since I don't know the structure of your Sweng class, I called the method to retrieve the result word getResultWord().

Replacing Position in Array Amongst Other Methods

Firstly - I thank anyone who takes the time to actually look at this since I feel like it's a rather annoying request.
I just completed a large challenge at the end of a series of Java 101 videos. The challenge is to design a guest list method ( as in for a restaurant or a party ) and some features along with it. This is really the first time I've written anything with multiple methods.
As the final step in this challenge, I need to design a method that allows the user to insert a new guest at a certain position while not removing any other guests. In other words, inserting a new guest and shifting the remaining guests downwards by a single index.
The issue I have is that the new guest is always inserted not only for the position I want, but also the position one after. It inserts itself twice and ends up over-writing the previous guest in the process.
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
public class GuestList_Edited {
public static void main(String[] args) {
// Setup for array, setup for scanner
String[] guests = new String[11];
Scanner scanner = new Scanner(System.in);
// A method to put these here so we don't always have to add guests. This method automatically inserts five guests into the guest list.
InsertNames(guests);
// Do-while loop to make sure that this menu screen shows up every time asking us what we want to do.
// It also makes certain that the menu shows up when we initially run the program.
do {
displayMenu(guests);
// This must remain in main for the rest of the program to reference it.
int option = getOption();
// If loop that will allow people to add guests
if (option == 1) {
addGuest(guests);
} else if (option == 2) {
RemoveGuest(guests);
} else if (option == 3) {
RenameGuest(guests);
} else if (option == 4) {
insertGuest(guests);
} else if (option == 5) {
System.out.println("Exiting...");
break;
}
} while (true);
}
// This displays the starting menu
public static void displayMenu(String SentArr[]) {
System.out.println("-------------");
System.out.println(" - Guests & Menu - ");
System.out.println();
GuestsMethod(SentArr); // Makes all null values equal to --
System.out.println();
System.out.println("1 - Add Guest");
System.out.println("2 - Remove Guest");
System.out.println("3 - Rename guest");
System.out.println("4 - Insert new guest at certain position");
System.out.println("5 - Exit");
System.out.println();
}
// This prints all the guests on the guest list and also adjusts the guest list when a guest is removed
public static void GuestsMethod(String RecievedArr[]) {
// If loop which prints out all guests on the list.
// "Null" will be printed out for all empty slots.
for (int i = 0; i < RecievedArr.length - 1; i++) {
// Make all null values and values after the first null value shift up in the array.
if (RecievedArr[i] == null) {
RecievedArr[i] = RecievedArr[i + 1];
RecievedArr[i + 1] = null;
}
// Make all null's equal to a string value.
if (RecievedArr[i] == null) {
RecievedArr[i] = " ";
}
// If values are not equal to a blank string value, assign a number.
if (RecievedArr[i] != " ") {
System.out.println((i + 1) + ". " + RecievedArr[i]);
}
// If the first value is a blank string value, then print the provided line.
if (RecievedArr[0] == " ") {
System.out.println("The guest list is empty.");
break;
}
}
}
// I've really got no idea what this does or why I need a method but the course I'm taking said to create a method for this.
// It gets the desired option from the user, as in to add a guest, remove a guest, etc.
static int getOption() {
Scanner scanner = new Scanner(System.in);
System.out.print("Option: ");
int Option = scanner.nextInt();
return Option;
}
// Allows users to add guests
public static String[] addGuest(String AddArr[]) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < AddArr.length; i++) {
// The below if statement allows the program to only ask for a name when a given space is "null", meaning empty.
if (AddArr[i] == " ") {
// so the loop runs until it hits a null value.
System.out.print("Name: ");
AddArr[i] = scanner.nextLine();
// Then that same value which was null will be replaced by the user's input
break;
}
}
return AddArr;
}
public static String[] RemoveGuest(String RemoveArr[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RemoveArr.length; i++) {
if (RemoveArr[number] != null) {
RemoveArr[number] = null;
break;
}
}
return RemoveArr;
}
// This inserts names into the array so we don't have to add guests everytime.
public static String[] InsertNames(String InsertNames[]) {
InsertNames[0] = "Jacob";
InsertNames[1] = "Edward";
InsertNames[2] = "Rose";
InsertNames[3] = "Molly";
InsertNames[4] = "Christopher";
// guests[5] = "Daniel";
// guests[6] = "Timblomothy";
// guests[7] = "Sablantha";
// guests[8] = "Tagranthra";
return InsertNames;
}
public static String[] RenameGuest(String RenamedGuests[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RenamedGuests.length; i++) {
if (RenamedGuests[number] != null) {
RenamedGuests[number] = null;
System.out.println("What would you like the guest's name to be?");
String NewName = scanner.next();
RenamedGuests[number] = NewName;
break;
}
}
return RenamedGuests;
}
// The final method which I am struggling with.
public static String[] insertGuest(String NewPositionArray[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
scanner.nextLine();
if (num >= 1 && num <= 10 && NewPositionArray[num - 1] != null)
System.out.print("Name: ");
String name = scanner.nextLine();
for (int i = 10; i > num - 1; i--) {
NewPositionArray[i] = NewPositionArray[i - 1];
NewPositionArray[num - 1] = name;
}
if (num < 0 || num > 10) {
System.out.println("\nError: There is no guest with that number.");
}
return NewPositionArray;
}
}
Once again, thanks. I realize I've probably done 1000 things wrong here. I appreciate your consideration.
I recommend you to declare ArrayList object instead of the normal array declaration; to avoid heavy work on the code where you can add an element into the ArrayList object with predefined add(int position, an element with your data type) method in a specific position and the ArrayList automatically will shift the rest elements to the right of it.
and for several reasons.
for more info about ArrayList in Java, please look at: -
Array vs ArrayList in Java
Which is faster amongst an Array and an ArrayList?
Here an example of add() method; which inserts the element in a specific position: -
Java.util.ArrayList.add() Method

How do i reference something in an array that the user has created

At the start of the code the user determines a number of keywords and the keyword strings themselves, they place this into an array. Lets say the user says 3 keywords and they are "music", "sports" and "memes". After all this, say the user inputs in the program "I like sports". I simply want the program to respond with "Let's talk about sports" after recognising that the user said sports which is in the array that the user has essentially created.
I want to reference a string the user has predetermined then print it along with a message
I can see the potential of this working using for loops and going through every article until you find a match, I haven't done much work with booleans yet so I just need some assistance punching out the code then learning from it
this all has to happen inside a while loop so when that's done they can use a different keyword and get the same boring response
thanks
note: I don't actually have any of this code I want in my program yet, this code is just to show you kind of how it fits into the greater scheme of things.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
String kwArray[];
String UserMessage;
String Target = "";
int numKw = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many keywords do you want?");
numKw = input.nextInt();
kwArray = new String[numKw];
System.out.print(System.lineSeparator());
input.nextLine();
for (int i = 0; i < numKw; i++) {
System.out.println("Enter keyword " + (i + 1) + ": ");
kwArray[i] = input.nextLine();// Read another string
}
for (int i = 0; i < numKw; i++) {
kwArray[i] = kwArray[i].toLowerCase();
}
int x = 0;
while (x == 0) {
System.out.println("Hey I'm a chatbot! Why don't you say something to me!");
System.out.println("These are the keywords you gave me");
for (String i : kwArray) {
System.out.print(i);
System.out.print(", ");
}
System.out.print(System.lineSeparator());
System.out.println("Or you can terminate the program by typing goodbye");
UserMessage = input.nextLine();
// Gives the user opportunity to type in their desired message
UserMessage = UserMessage.toLowerCase();
if (UserMessage.contains("?")) {
System.out.println("I will be asking the questions!");
}
if (UserMessage.contains("goodbye")) {
x = 1;
}
}
input.close();
}
}
If I am getting the question right, you want to check whether an element exists in the submitted keywords and want to reference it back if you further processing.
For this, instead of an array you could use a HashSet which can check the existence any element in O(1).
Updated the code, but I still feel your query is the same what I understood, putting the exact example of your use case below:
Scanner input = new Scanner(System.in);
Set<String> set = new HashSet<String>();
int keywords = input.nextInt();
for (int i=0; i<keywords; i++) {
//add to set set like:
set.add(input.readLine());
}
String userComment = input.readLine();
String[] userCommentWords = userComment.split(" ");
//you can iterate over the words in comment and check it in the set
for (int i=0; i<userCommentWords.length; i++) {
String word = userCommentWords[i];
if (set.contains(word)) {
System.out.println("Let's talk about "+word);
}
}

How to check if user defined input is unique in a vector of an Object type?

I am doing a school project based on a stock control system. I want the prducts to have their product id as their primary key. Upon input of the product id I want to traverse the vector inorder to check whether that id is already existent; If this is the case, then the user is prompted to enter a new, unique id. I wrote the following code:
String chkpid = "[0-9]{4}[P]";
valid = false;
matchid = false;
do{
System.out.println("Enter Product ID (4-digit code followed by the Letter P): ");
pid = sc.next();
if(pid.matches(chkpid)){
for(int i = 0; i < temp.size(); i ++){
st = temp.elementAt(i);
if(pid.equals(st.getPid()))
matchid = true;
else
matchid = false;
}
if(matchid == true){
valid = false;
System.out.println ("Product ID already in use. Please Enter an uncommon ID.");
}else
valid = true;
}else
System.out.println ("Invalid Product ID Format.");
}while(valid != true);
Stock s1 = new Stock(name, qty, cost, pid);
temp.add(s1);
added = true;
System.out.println ("Product was Added Succesfully!");
System.out.println ();
}
This seems to work fine, but I noticed that it only stops the user to enter an id which is the same as the previous element. For example if there are 2 products with different id's in the vector, and the user is inputting a new product with the same id as the 1st element, it is accepted and added to the vector (which obviously is wrong!). However, if the input id is equal to the id of the 2nd element, the user is prompted to enter a new one (thus doing what it is supposed to do). How can I fix this? P.S I am new to java, so sorry for any stupid mistakes!
I have gone through this step by step and I cannot seem to find where my logic is faulty!
Moreover, are there any better ways to implement this?
Try with this
for(int i = 0; i < temp.size() && matchid == false; i ++){
st = temp.elementAt(i);
if(pid.equals(st.getPid()))
matchid = true;
else
matchid = false;
}
You need to stop the loop when you find a similar id to keep the right value in your boolean matchid
For a better way off implementation, check Vector.contains(Object o). But you'll need to create a Stock object with the new pid to compare two Stock object
EDIT :
public static void main(String[] main){
int valueToCheck = 85;
Vector<Integer> list = new Vector<Integer>();
list.add(5);
list.add(15);
list.add(85);
list.add(1);
list.add(145);
boolean matchid = false;
int i = 0;
while (i < list.size() && matchid == false){
if(list.elementAt(i) == valueToCheck)
matchid = true;
else
matchid = false;
++i;
}
System.out.println(i + " : " + matchid);
}
My output is 3 : true meaning that I exit the loop when I found the value 85
and 5 : false with and other value

Categories

Resources