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);
Related
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
}
I am currently working on Java code. Basically, the int input works. However, if I type in a character, the whole system crashes. My question is as to what needs to be changed in the below code in order for the user to receive a message stating that only an int is the valid input, and to try again if they input a character.
do {
System.out.println("How many players would like to participate in this game?\t(2-4 players)");
numberOfPlayers = in.nextInt();
} while(in.hasNextInt());
numberOfPlayers = in.nextInt();
I personally prefer to use a while loop for this sort of thing rather than the do/while. Not that there is anything wrong with the do/while, I just feel it's more readable to use the while loop.
I agree with others here, accept String digits from the User instead of Integer. In my opinion it saves you other possible problems down the road and you have no need to purposely apply a try/catch mechanism should the User supply an invalid entry. It also allows you to easily apply a mechanism to quit the application which, again IMHO, should be made available to all Console app's.
You've got your answer for carrying out the task using a do/while loop but I would like to show you another way to do this sort of thing:
Scanner in = new Scanner(System.in);
String ls = System.lineSeparator();
int numberOfPlayers = 0;
String userInput = "";
while (userInput.equals("")) {
// The Prompt to User...
System.out.print("How many players would like to participate in this game?" + ls
+ "2 to 4 players only (q to quit): --> ");
userInput = in.nextLine();
// Did the User enter: q, quit (regardless of letter case)
if (userInput.toLowerCase().charAt(0) == 'q') {
// No, the User didn't...
System.out.println(ls + "Quiting Game - Bye Bye.");
System.exit(0); // Close (exit) the application.
}
/* Did the User supply a string representation of a numerical
digit consiting of either 2, 3, or 4. */
if (!userInput.matches("[234]")) {
// No, the User didn't...
System.out.println("Invalid input! You must supply a number from 2 to 4 "
+ "(inclusive)." + ls + "Try again..." + ls);
userInput = "";
continue; // Loop again.
}
// Convert numerical string digit to an Ingeger value.
numberOfPlayers = Integer.parseInt(userInput);
}
System.out.println(ls + "The Number of players you provided is: --> "
+ numberOfPlayers);
You will notice that the Scanner#nextLine() method is used to accept User input as a String. This now means that we need to validate the fact that a string representation of a Integer numerical digit (2 to 4 inclusive) was supplied by that User. To do this you will notice that I used the String#matches() method along with a small Regular Expression (RegEx) which consists of the following string: "[234]". What this does in conjunction with the String#matches() method is it checks to see if the string value in the userInput variable contains either a single "2", a single "3", or a single "4". Anything else other than any one of those three digits will display this message:
Invalid input! You must supply a number from 2 to 4 (inclusive).
Try again...
and, force the User make yet another entry.
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);
}
Hi I am encountering a problem with a uni project I am working on. I am trying to validate the input so that the BookID that is entered when attempting to loan the book, is only valid if it exists in the array named 'BookList'. At the minute I have it working so that it validates it to make sure that an integer is entered, and not letters or negative numbers.
I have tried endlessly but I am stuck completely?? any tips or help, I would much appreciate it.
thanks
//loan a book method
public void loanBook() {
int loanID;
do {
System.out.println("Please enter the Book ID of the book that you wish to borrow");
while (!input.hasNextInt()) { // checking that the ID entered is an integer - validation
System.out.println("That is not an integer");
input.nextLine(); //pushing the scanner on
}
loanID = input.nextInt(); //setting the loanID variable equal to the input from the scanner.
}
while (loanID < 0 || loanID > 100000000); //VALIDATION - NEED TO CHANGE SO THAT WHILE LOAN ID EXISTS IN ARRAY LIST ????
for (int i = 0; i < BookList.size(); i++) { //for loop to go through and check for the ID entered to remove the book that it corresponds to
if (BookList.get(i).getBookID() == loanID ) {
System.out.println("The book named : " + BookList.get(i).getTitle() + " has now been taken out on loan. Please return within 2 weeks!");
BookList.get(i).setStatus("On Loan");;
}//end of if statement
}//end of for loop
} //end of return book method
You can use the .contains() method for Arraylists. You just need to make sure you are removing items depending on their status.
if(bookList.contains(loanID)){
//logic for book exists
}else{
//book is on loan.
}
Now as I said you need to make sure you are doing proper verification for removing of the books on loan etc for this to work. The way you have your logic right now is doing a LOT of unnecessary work with your loops. This way you can easily scan the list and find the item needed. Of course there are better ways to set up your lists etc but this should work keeping your code very similar.
EDIT
You requested information on how you would find the index of the item after you have verified it exists. This is still very simple. Once you have verified that the item exists you would use the line:
int index = bookList.indexOf(loanID);
This will return the index in your ArrayList for the location of the book. Once you have the index you can begin doing everything you were doing before with:
bookList.get(index).getBookId();
or
bookList.get(bookList.indexOf(itemId)).getBookId();
This is almost exactly what you were doing previously but cut down to 3 lines and can be made even shorter.
if (BookList.contains(loanID)) {
int index = BookList.indexOf(loanId);
if (!BookList.get(index).getStatus().equals("On Loan")) {
System.out.println("The book named: " + BookList.get(index).getTitle() + " has now been taken on loan.");
BookList.get(index).setStatus("On Loan.");
}else{
System.out.println("Book is on loan already.");
}
}else{
//logic for not existing.
}
Create a variable int isExist = 0; After getting the input from user...go through the array and see if that book exists. Then make isExist=1; And then of the loop just make if statement
if( isExist == 0) {
System.out.println("Book is not found");
}
By the way once you have found the book in the array you want to break out of the loop using break;
I am trying to create a program for an assignment in Java and are looking for a push in the right direction. I am currently taking the class online so asking a teacher for help is not an option for me.
I am trying to create a simple java program that allows a user to enter their first name and last name, and their requested seat number. If the seat is taken, the program is supposed to find the nearest available seat. So far I have succeeded at getting all the input from the user (albeit in a roundabout way) and creating and printing an array.
Question
Can I store boolean values in an array? I just want to store false if the seat is taken and then have and if else statement test for true or false, and store a false if the value returned is true(very confusing but thats my train of thought) is there an easier way to go about this? Also how would I also store the persons first and last name with that boolean value? Do I have to create a seperate array? I have attached my code so far that succeeds in getting the user info and printing out an array.
//Import scanner and arrays
package airlinereservations;
import java.util.Scanner;
import java.util.Arrays;
public class AirlineReservations {
public static void main(String[] args) {
//Print the header
System.out.println("___________________________________");
System.out.println("|WELCOME TO FLY BY NIGHT AIRLINES!|");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
// Promt user for first and last name
System.out.println("Please enter your first name:");
Scanner scan= new Scanner(System.in);
String first = scan.nextLine();
System.out.println("Please enter your last name:");
String last = scan.nextLine();
//Greet the user
System.out.println("Hello! " + first + " "+ last);
//Get the requested seat
System.out.println("Please enter your requested seat row number 1-9:");
int rowz = scan.nextInt();
System.out.println("Please enter your requested seat column number 1-4:");
int colz = scan.nextInt();
//Tell the user if the seat is already taken
if(int rowz == rowz, System.out.println("This seat is already taken!"));
else(return true);
//Print out the array
int[][] Seating= new int[9][4];
for(int row=0; row<Seating.length; ++row){
for(int col=0; col<Seating[row].length; ++col){
Seating[row][col] = (row + col) % 9 + 1;
for(int ro=0; ro<Seating.length; ++ro);
}
System.out.println();
for(int col=0; col<Seating [row].length; ++col)
System.out.print(Seating[row][col]);
}
System.out.println();
}
}
For a push in the right direction, as you said, I see two quick options to consider:
One would be to add a Map. This would allow you to store a bunch of key-value pairs which you could use to represent seats, and whether or not they are taken.
Another option is to create a Seat class, that has a field for seatName and whether or not it is taken, and you could create an Array of these seat objects.
If you don't know where to begin on implementing either of those, I will help you, but I challenge you to at least try implementing one or the other first.
EDIT
Or, even more simply, you could create a two-dimensional array holding strings, like this:
String[][] seats = new int[numberofseats][2];
seats[0][0] = "Seat Number 1";
seats[0][1] = "true";
And you can force that second dimension to only hold values true or false, and later check them like this:
if(seats[0][1].equals("true")) // Then seat number 1 is taken
This might not be the best solution as far as error handling, but it is a possibility.
EDIT 2 If you were to create a seat class, I would set it up like this:
public class Seat{
private String seatName;
private boolean isTaken;
public Seat(String s, boolean t){
this.seatName = s;
this.isTaken = t;
}
public boolean isSeatTaken(){
return this.isTaken;
}
}
Then, later you can do something like this:
ArrayList<Seat> myArrayList = new ArrayList<Seat>(); // Or a regular array if you prefer
// Add elements
// Below checks if first seat in list is taken
boolean firstSeatTaken = myArrayList.get(0).isSeatTaken();