how to make sure an integer number is unique / not repeated - java

program is where users enter their details and they are searched by their social security numbers
i have the program running but i can enter the same social secirty number over and over
how can i make sure that users making input enters a unique number??
Scanner keyboardIn = new Scanner(System.in);
//Create objects of FileWriter and PrintWriter classes
FileWriter PersonFile = new FileWriter("persons.txt");
PrintWriter pw = new PrintWriter(PersonFile);
int PPSNumber
System.out.print("Enter PPS Number:");
PPSNumber = keyboardIn.nextInt()
pw.println("PPS Number: " +PPSNumber+ " ");
Thank you all

Collect the integers in a Set of type HashSet<Integer>, and before adding, check whether or not the set already contains() the value you're trying to add.

You can keep social security numbers in a Set and check its size every time you add new item, if size remained same the item is repetitive because Set does not let repetitive items:
Set<Integer> securityNumbers = new HashSet<>();
securityNumbers.add(10);
int securityNumbersSize = securityNumbers.size();
securityNumbers.add(10);
if(securityNumbers.size() == securityNumbersSize){
//Item is repeated
}

Related

How to add multiple variables as a single value in an arraylist?

today I need some help with adding 4 user defined string, 2 int and 4 double variables into an arraylist as one single index.
Eg: (I'll cut down some of the variables for you, and keep in mind that sc is my scanner object and test results are out of 100)
System.out.print("enter your name")
String name = sc.next();
System.out.print("enter your test results")
double results = sc.nextDouble();
System.out.print("enter your mobile number")
int mobile_num = sc.nextInt(); //I may change this to a string
Now from here, I want to capture these inputs and store them in the array under the number 1 or the user's name. I also want to know how to use this same array to store unlimited inputs from the user through the code mentioned above.
Thanks in advance!
Create your own class UserInput which keeps 10 fields and then generalise a List with this type:
List<UserInput> list = new ArrayList<>();
list.add(new UserInput(name, results, mobile_num, ...));
If you want to associate a user's name with his corresponding input, you had better consider a Map<String, UserInput>:
Map<String, UserInput> map = new HashMap<>();
map.put(name, new UserInput(results, mobile_num, ...));

Adding user input in Arraylist

I am new to JAVA and this is what I have to do:
Accept a set of marks (out of 100). The user should press the Enter button after each mark is entered and the mark should then be added to an ArrayList of Integers.
This is what I have so far:
int score = Integer.parseInt(marksinput.getText());
ArrayList<Integer> marks = new ArrayList();
Collections.addAll(marks, score);
String out = "";
String Out = null;
int[] studentmarks = {score};
for (int item : studentmarks) {
marksoutput.setText(""+item);
}
if (score > 100) {
marksoutput.setText("Enter marks\n out of 100");
}
This only adds one mark in the arraylist and I need user to input as many marks he wants. I know that my arraylist is wrong, which is why it only takes 1 number but I do not know how to make all the input numbers go in arraylist. What I have is that it takes the number and if user inputs another number, it just replaces the older number. I want it to display both the numbers not just one. Any help is appreciated and thank you in advance!☻☻
(This is not a duplicate even though others have the same title)
In case what you are after is a program that adds any integer typed by the user into an ArrayList, what you would have to do is the following:
Scanner scanner = new Scanner(System.in);
List<Integer> ints = new ArrayList<Integer>();
while(true)
ints.add(scanner.nextInt());
What this program will do, is let the user input any number and automatically puts it into an ArrayList for the user. These integers can then be accessed by using the get method from the ArrayList, like so:
ints.get(0);
Where the zero in the above code sample, indicates the index in the ArrayList from where you would like to retrieve an integer.
Since this website is not there to help people write entire programs, this is the very basics of the ArrayList I have given you.
The ArrayList is a subclass of List, which is why we can define the variable using List. The while loop in the above example will keep on going forever unless you add some logic to it. Should you want it to end after executing a certain amount of times, I would recommend using a for loop rather than a while loop.
Best regards,
Since it seems you are really new,
What you are looking for is a for-loop
From the Java documentation, he is the syntax of a for-loop in Java
for (initialization; termination; increment) {
statement(s)
}
Initialization: Obviously you want to start from 0
Termination: you want to stop after 100 inputs, so that's 99 (starting from zero)
Increment: you want to "count" one by one so count++
for(int counter = 0; counter < 100; counter++) {
//Ask user for input
//read and add to the ArrayList
}
So before you enter the for-loop you need to initialize the ArrayList, and a Scanner to read input:
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList();
for(int counter=0; counter < 100; counter++) {
System.out.println("please enter the " + counter + " number");
int x = sc.nextInt();
list.add(x);
}

Using a Scanner with a String Splitter

I am trying to use a string splitter to display user input e.g. 1,2 coordinates to display on a console. I don't get any errors when I run my code. However, my attempt to use the splitter does not seem to work.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
System.out.println("Please enter coordinates in the correct format.");
System.out.println("\nPlayer 1 Please take your turn:");
continue;
}
System.out.println("\nEnter Mine location:");
System.out.println("\nPlease Enter x position for your Mine:");
System.in.read(byt);
str = new String(byt);
row = Integer.parseInt(str.trim());
System.out.println("\nPlease Enter y position for your Mine:");
System.in.read(byt);
str = new String(byt);
col = Integer.parseInt(str.trim());
Your use of System.in.read(...) is dangerous code and is not doing what you think it's doing:
System.in.read(byt); // *****
str = new String(byt);
row = Integer.parseInt(str.trim());
Instead use a Scanner, something that you already have, and either call getNextInt() on the Scanner, or get the line and parse it.
Also, you never use the Strings held in the coordinates array -- why get the Strings if you are ignoring them?
You ask about:
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
str = scanner.nextInt().split(",");
but then see that the compiler won't allow this since you're trying to call a method on the int primitive that scanner.nextInt() returns.
My recommendation to use Scanner#nextInt() was as a replacement for you misuse of System.in.read(...). If instead you want the user to enter two numbers on one line, separated by a comma, then you're best bet is to use String.split(","), although, I think it might be better to use String.split("\\s*,\\s*") to get rid of any white space such as spaces hanging about. This way the split should work for 1,1 as well as 1, 2 and 1 , 2, and then you can parse the items held in the array via Integer.parseInt(...).

How can i create as many scanners as the user wants

I want to write a code that will allow the user to pick how many scanners he wants to use. First I created a simple scanner and assigned an int to it
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
now the user will enter ANY integer (ex. 7). Then I want the program to create an array of scanners that will then allow a number of lines of input (in this case 7). Any help is appreciated!
To create a specific number of objects and store them somewhere you can easily use arrays:
Scanner[] scanners = new Scanner[num_of_scanners];
At this point you will have an array of null scanner objects. To declare them properly you have to use a loop like this:
for (int i = 0; i < scanners.length; i++)
{
scanners[i] = new Scanner(System.in);
}
Now you succesfully initialized all the scanners. To get your scanner at certain index see the example below:
Scanner first_scanner = scanners[0];
More on arrays here.

Prevent duplicate values in an array

How can i ask the user to reenter again if the value from the PID is already existed in the array ?
ex: he enter A then B and he enter A again, then the A he entered from the last will not be accepted because it's already existed.
int[] Process = {};
int NumberofProcess = 0;
String[] PID = new String[10]; //Proces ID
System.out.print("Enter a number of Process from 1 to 10 : ");
while(bError){
if(scan.hasNextInt()){
NumberofProcess = scan.nextInt();
}else{
scan.next();
continue;
}
bError = false;
}
//---------------- Ask for the user to input for the Process id AT and EX -------
for(int i=0;NumberofProcess > i;i++){
System.out.print("Please Enter a ProcessID " + (i + 1) + " : ");
PID[i] = scan.next();
}
I'd not use an array but a LinkedHashSet (assuming you want to preserve input order). Then check using the set's contains(...) method or try to add the PID using add(...) and check the return value (false if it has not been added, i.e. if it already existed in the set).
If you can use a Set instead, do as Thomas suggests and use either a normal HashSet if the order of the values is not important, and LinkedHashSet otherwise.
If you must use an array, use `Arrays.binarySearch' to check if the array already contains the string:
String pid = scan.next();
if (Arrays.binarySearch(PID, pid) < 0) {
PID[i] = pid;
}
Note: of course you need to import java.util.Arrays.
What you need is to create a structure were you would store the PID that user has already put in you system.
Then you should validate every new input, against items in that storage. If you find a collision you just notify user about it and repeat the process until he input valid data or choose to exit.
In Java you can used dedicated data structure called collections, that would speed up the finding process. The simple ArrayList wild be enough for your needs.
To declare
Collection<String> storage = new ArrayList<>();
To use
boolean wasStored = storage.contains(input);

Categories