This is where it asks the user to input their information then run checkID();
to compare already existing ID's in the file to the user input
public static void newRecord()
{
System.out.println("Enter your full name: ");
name = input.nextLine();
name = input.nextLine();
System.out.println("Enter your age: " );
age = input.nextInt();
input.nextLine();
System.out.println("Enter your id: ");
id = input.nextInt();
checkID();
if(checkID())
{
start();
}
else
{
System.out.println(id);
addRecords();
}
}
This is where i check the ID's. I check where ID: starts and then look for the value of id, but it doesn't detect the ID in the file and it creates the exact Id rather than telling the user the id has already been taken
public static boolean checkID()
{
Scanner y = new Scanner("Names.txt");
while(y.hasNextLine())
{
final String idChecker = y.nextLine();
if(idChecker.startsWith("ID: ") && idChecker.substring(4).equals(String.valueOf(id)))
{
System.out.println("Sorry, this ID has already been taken, please try again.");
y.close();
return true;
}
}
y.close();
return false;
}
You need to pass a File object to your Scanner instead of the file name.
The other issue is that you should only call addRecords() once you've checked all the ids in Names.txt i.e. once your while loop exits without going into the if block.
You should also use equals() instead of contains() because otherwise you can't create an id 11 if 1 already exists!
Your checkID() method should ideally return a boolean indicating an already existing id and the caller should then call start() or addRecords() accordingly.
public static boolean checkID()
{
try {
Scanner y = new Scanner(new File("Names.txt")); // pass File instance
while(y.hasNextLine())
{
final String idChecker = y.nextLine();
if(idChecker.startsWith("ID: ") &&
idChecker.substring(4).equals(String.valueOf(id)))
{
System.out.println(
"Sorry, this ID has already been taken, please try again.");
y.close();
return true;
}
}
y.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
Note that I'm calling Scanner#close() when done. Your newRecord() method should look something like
public static void newRecord()
{
System.out.println("Enter your full name: ");
name = input.nextLine();
System.out.println("Enter your age: " );
age = input.nextInt();
System.out.println("Enter your id: ");
id = input.nextInt();
System.out.println(id);
if(checkID())
{
start();
}
else
{
addRecords();
}
}
Related
public class Source
{
String[][]customerDetails=new String[5][3];
Source()
{
customerDetails[0][0]="1001":
customerDetails[0][1]="Raj";
customerDetails[0][2]="Chenna";
customerDetails[1][0]="1008";
customerDetails[1][1]="Akshay";
customerDetails[1][2]="Pune";
customerDetails[2][0]="1002";
customerDetails[2][1]="Simrath";
customerDetails[2][2]="Amristar";
customerDetails[3][0]="1204";
customerDetails[3][1]="Gaurav";
customerDetails[3][2]="Delhi";
customerDetails[4][0]="1805";
customerDetails[4][1]="Ganesh";
customerDetails[4][2]="Chennai";
}
public static void main(String args[]) throws Exception
{
Source src=new Source();
}
}
Here is one way to get Customer Details based on a supplied Customer ID (read comments in code):
String[][]customerDetails = new String[5][3];
customerDetails[0][0]="1001";
customerDetails[0][1]="Raj";
customerDetails[0][2]="Chenna";
customerDetails[1][0]="1008";
customerDetails[1][1]="Akshay";
customerDetails[1][2]="Pune";
customerDetails[2][0]="1002";
customerDetails[2][1]="Simrath";
customerDetails[2][2]="Amristar";
customerDetails[3][0]="1204";
customerDetails[3][1]="Gaurav";
customerDetails[3][2]="Delhi";
customerDetails[4][0]="1805";
customerDetails[4][1]="Ganesh";
customerDetails[4][2]="Chennai";
// Scanner object to get keyboard input from User.
Scanner userInput = new Scanner(System.in);
// Prompt loop. Keep looping until 'q' is entered to quit.
while (true) {
System.out.print("Enter a four digit ID number (q to quit): --> ");
String idNum = userInput.nextLine(); // Get User input...
// If 'q' is entered then quit.
if (idNum.equalsIgnoreCase("q")) {
System.out.println("Bye-Bye");
break;
}
/* VALIDATE input. Make sure it's a 4 digit numerical value.
If it isn't then inform User of Invalid Entry and allow
the User to try again. */
if (!idNum.matches("[0-9]{4}")) {
System.out.println("Invalid ID Number (" + idNum + ")! Try Again...\n");
continue;
}
// Display ID details...
boolean found = false; // Flag to indicate that Customer ID was found.
for (String[] customer : customerDetails) {
if (customer[0].equals(idNum)) {
System.out.println("Customer ID:\t" + customer[0]);
System.out.println("Customer Name:\t" + customer[1]);
System.out.println("Customer City:\t" + customer[2]);
System.out.println();
found = true;
break;
}
}
if (!found) {
// If Customer ID was not found!
System.out.println("Can not find the Customer ID (" + idNum
+ ") within the Customers List!\n");
}
}
I am attempting to have my user read from my menu and make a selection either option 1 (add a product name, store name, purchase date and cost), option 2 display the arrayList with the purchase objects the were inputted and option 3 exit the program and thank the user for using my program all while have exceptions to ensure that the user doesn't input and valid entries. Now I need to be able to store to a txt file and have the ability to pull it back up for review or modification.
I built my menu and and I believe that I have setup my arrayList correctly for proper user input, I have methods for each string that the user will be inputting and exceptions to ensure that the inputs are valid
public static void main(String[] args) throws Exception {
//Create menu options
TheMenu();
}
public static void TheMenu() {
Scanner input = new Scanner(System.in);
String purchase[] = new String[4];
int option;
do { // loop until Exit (option 3) is selected
System.out.println("\nMenu Options");
System.out.println("\n1 Add a purchase");
System.out.println("\n2 Display a purchase");
System.out.println("\n3 Exit");
option = input.nextInt();
if (option == 1) {
displayPurchaseObjects(purchase);
}
if (option == 2) {
System.out.println();
}
while (option == 3)
System.out.println("Thank you for using purchase programmer!");
System.exit(3);
//Create a list to store Purchase objects
ArrayList<String> displayPurchaseObjects = new ArrayList<>();
while(input.hasNext()) {
System.out.println("Enter the product name ");
String productName = input.next();
System.out.print("Enter the store name");
String storeName = input.next();
System.out.println("Enter the purchase date (i.e. 06/30/2019) ");
int purchaseDate = input.nextInt();
System.out.println("Enter the cost ");
double cost = input.nextDouble();
}
}
}
public void productName(String productName) {
try {
for(int i = 1; i < productName.length(); i++) {
}
}
catch(Exception e) {
System.out.println("Please enter a product name ");
}
}
public void storeName(String storeName) {
try {
for(int i = 1; i < storeName.length(); i++) {
}
}
catch(Exception e) {
System.out.println("Please enter a store name");
}
}
public void purchaseDate(String date) {
DateTimeFormatter format = DateTimeFormatter.ofPattern(date);
try {
format.parse(date);
}
catch(Exception e) {
System.out.println("Invalid date");
}
}
public void cost(double newCost)
throws InputMismatchException{
double cost;
if(newCost >= 1)
cost = newCost;
else
throw new InputMismatchException("Cost must be a integer and more the $0 ");
}
I am receiving a compilation error because of a "}" which I cannot find the cause and the program should be allowing me to make a selection (1,2 or 3) and the should be able to add my purchase objects to my "displayPurchaseObjects" arrayList
If I have understood your question clearly, the problem at hand is the compilation error - not able to find a "}".
In your code, you are missing out the "}" after this -
do { // loop until Exit (option 3) is selected
System.out.println("\nMenu Options");
System.out.println("\n1 Add a purchase");
System.out.println("\n2 Display a purchase");
System.out.println("\n3 Exit");
option = input.nextInt();
if (option == 1) {
displayPurchaseObjects(purchase);
}
if (option == 2) {
System.out.println();
}
} while (option == 3);
System.out.println("Thank you for using purchase programmer!");
// Non zero exit code is only for abnormal termination. Use 0.
System.exit(0);
I am trying to see if the password that was user inputted in method addUser() matches the password user inputted in the method deleteUser(). Both methods look into the users arraylist that is full of FacebookUser objects, However, I cannot figure out how to match the appropriate passwords from each method.
I have tried multiple codes I can hardly even remember, sometimes I'd always get "incorrect password" returned even when it is correct But whenever I had only one object in my arraylist it would work until I added another user. It would make both users end up with the same password.
public class Facebook extends FacebookUser implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
Scanner input = new Scanner(System.in);
private ArrayList<FacebookUser> users;
public Facebook(String username, String password) {
super(username, password);
users = new ArrayList<>();
}
// prints users
public void listUsers() {
if( users.isEmpty())
{
System.out.println("List is empty");
}
else
{
for (FacebookUser users : this.users)
{
System.out.println("Username: " + users.getUsername());
}
}
}
// adds a user
public void addUser() {
//creating an instance of FacebookUser class
FacebookUser user1 = new FacebookUser();
System.out.println("Enter username to add: ");
String newUser = input.nextLine();
user1.setUsername(newUser);
// using the setter method in UserAccount to set the username for "fb" object
//if statement checks if any object contains the same username
if (users.contains(user1)) {
System.out.println("Error, username already exists");
}
else {
System.out.println("Please enter password: ");
String password = input.nextLine();
System.out.println("Please enter password hint: ");
String passwordHint = input.nextLine();
FacebookUser user2 = new FacebookUser();
//creating another object for the "official" new user
user2.setPassword(password);
user2.setUsername(newUser);
user2.setPasswordHint(passwordHint);
users.add(user2);
System.out.println(newUser + " has been added");
}
}
// deletes a user
public void deleteUser() {
FacebookUser user1= new FacebookUser();
System.out.println("Enter username you want to remove: ");
String removeUser = input.nextLine();
user1.setUsername(removeUser);
if (users.contains(user1)) {
System.out.println("Enter password");
String checkPassword = input.nextLine();
user1.setPassword(checkPassword);
if (user1.password.equals(checkPassword)) {
users.remove(user1);
System.out.println(removeUser + " has been removed");
} else {
System.out.println("Incorrect password");
}
} else {
System.out.println("User does not exist");
}
}
If you are not overriding the implementation of contains your code will not work. Try something similar to this .
public void deleteUser() {
FacebookUser user1= new FacebookUser();
System.out.println("Enter username you want to remove: ");
String removeUser = input.nextLine();
boolean isPresent = false;
for(FacebookUser user:users){
if(user.getUsername.equals(removeUser)){
isPresent = true;
System.out.println("Enter Password");
password = sc.nextLine();
if(user.getPassword.equals(password)){
users.remove(user);
break;
}else{
System.out.println("Incorrect Password");
}
}
}
if(!isPresent){
System.out.pritln("User does not exist");
}
}
Problem is, in deleteUser(), you are setting the user inputted password to user1 before checking the password with if (user1.password.equals(checkPassword)). So, this if condition is always true.
I have commented that unnecessary line in below code.
(I assume you have overridden equals() method correctly in FacebookUser class. Because, contains() and remove() methods rely on equals() method.)
public void deleteUser() {
FacebookUser user1= new FacebookUser();
System.out.println("Enter username you want to remove: ");
String removeUser = input.nextLine();
user1.setUsername(removeUser);
if (users.contains(user1)) {
System.out.println("Enter password");
String checkPassword = input.nextLine();
// I commented this line
//user1.setPassword(checkPassword);
if (user1.password.equals(checkPassword)) {
users.remove(user1);
System.out.println(removeUser + " has been removed");
} else {
System.out.println("Incorrect password");
}
} else {
System.out.println("User does not exist");
}
}
Try This.
When you are using user.contain(user1) it will compare all the fields of user 1 in user. ie it will check for a user having same username and password as user1. But the password is not set for this user 1 before. Hence, it will never find it in the list.
and when you use .remove() on arraylist, it takes index as argument. So always pass index of the user to be removed and not the user.
If still any error, post the error in the comment and I will let you know the solution.
public void deleteUser() {
FacebookUser user1= new FacebookUser();
System.out.println("Enter username you want to remove: ");
String removeUser = input.nextLine();
int i=0;
for(FacebookUser users:this.users)
{
boolean present = false;
if(users.getUserName().equals(removeuser))
{
present = true;
System.out.println("Enter password");
String checkPassword = input.nextLine();
users.setPassword(checkPassword);
if(users.getPassword().equals(checkPassword))
{
this.users.remove(i);
System.out.println(removeUser + " has been removed");
break;
}
else
System.out.println("Incorrect password");
}
i++;
}
if(!present)
System.out.println("User does not exist");
}
I am creating a booking project in NetBeans, I am first implementing a booking controller that will validate user input using the Java scanner. I would like to test the code and input data in the terminal. When I run the output of the code terminal the terminal just shows " Build successful". And shows none of the systems out print code line. I am not too sure what is wrong with the code please see below
package fitnessclassapp;
import java.util.Scanner;
public class BookingController {
private Scanner input = new Scanner (System.in);
Customer customer = new Customer ();
// customer enter details and the details are validated
private String Customer () {
String customerName = "";
int customerAge = -1 ;
String membership = "";
boolean isName;
System.out.println( "Please enter your name " );
do {
// name of condition HasNext will check the user input
if ( input.hasNext()) {
customerName = input.nextLine();
isName = true;
// add a boolean
}else
System.out.println ( "You have provided incorrect information");
isName = false;
input.next();
}while ( !isName );
System.out.println(customerName);
return customerName;
}
}
Try this code,
package fitnessclassapp;
import java.util.Scanner;
public class BookingController {
private Scanner input = new Scanner(System.in);
// Customer customer = new Customer();
// customer enter details and the details are validated
private String Customer() {
String customerName = "";
int customerAge = -1;
String membership = "";
boolean isName;
System.out.println("Please enter your name ");
do {
// name of condition HasNext will check the user input
if (input.hasNext()) {
customerName = input.nextLine();
isName = true;
// add a boolean
} else
System.out.println("You have provided incorrect information");
isName = false;
input.next();
} while (!isName);
System.out.println(customerName);
return customerName;
}
public static void main(String[] args) {
BookingController con = new BookingController();
con.Customer();
}
}
if any issue inform.
I have to write a program that asks the user for his name, address and phone number. When the data is entered the program shall print the data and ask the user to verify the data by entering yes or no. This process shall be repeated until the user is satisfied and answers yes to the question.
Now, at this moment I am able to pop-up a single prompt (in my case asking only the user's name). But what if I want to add multiple question (i.e. asking address and telephone number) and happen the same thing? How could I do that?
My code:
package userinfo;
import java.util.Scanner;
import sun.security.krb5.SCDynamicStoreConfig;
public class UserInfo {
public static void main(String[] args) {
String varify;
String yes = "yes";
String no = "no";
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = input.next();
System.out.println("Your input was: "+name);
System.out.println("Varify by yes or no: ");
while (true) {
varify = input.next();
if (varify.equalsIgnoreCase(yes)) {
System.out.println("Varified! Your name is: " + name);
} else if (varify.equalsIgnoreCase(no)) {
System.out.println("Type your name again: ");
}
}
}
}
You can extract this code to a method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName = readFieldAndVerify(input, "Enter your name: ");
String userAddress = readFieldAndVerify(input, "Enter your address: ");
String userPhoneNumber = readFieldAndVerify(input, "Enter your phone number: ");
}
private static String readFieldAndVerify(Scanner input, String prompt) {
while (true) {
System.out.print(prompt);
String field = input.next();
System.out.println("Are you sure (yes / no)?");
String verify = input.next();
if (verify.equalsIgnoreCase("yes")) {
System.out.println("Verified!");
return field;
} else {
System.out.println("Canceled");
}
}
}
EDIT Added logic for more questions... Expand it in similar fashion for everything you need. You could expand this code into a single method as well so you avoid code replication. Check answer from user alaster for an example.
Try this. It will store the name variable in case you want to use it further.
We use a boolean to keep asking the user to input his name until he validates it.
Of course, you can still use while(true) and then break if the name is valid, but I prefer this method since the code is more clear and easier to understand.
private static boolean isVerified(String verify) {
if (verify.equalsIgnoreCase("yes")) {
return true;
} else if (verify.equalsIgnoreCase("no")) {
return false;
} else
return false;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean validName = false;
boolean validTelephoneNo = false;
boolean validAddress = false;
String name="";
String telephoneNo="";
String address="";
while (!validName) {
System.out.print("Enter your name: ");
name = input.next();
System.out.println("Are you sure your name is " + name + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your name is: " + name);
validName = true;
} else {
System.out.println("Not verified! Please type your name again.");
}
}
while (!validTelephoneNo) {
System.out.print("Enter your telephone nummber: ");
telephoneNo = input.next();
System.out.println("Are you sure your telephone number is " + telephoneNo + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your telephone number is: " + telephoneNo);
validTelephoneNo = true;
}
else {
System.out.println("Not verified! Please type your telephone number again.");
}
}
while (!validAddress) {
System.out.print("Enter your address: ");
address = input.next();
System.out.println("Are you sure your address is " + address + "?");
final String verify = input.next();
if (isVerified(verify)) {
System.out.println("Verified! Your address is: " + address);
validAddress = true;
}
else {
System.out.println("Not verified! Please type your address again.");
}
}
System.out.println("Done, here is your info:");
System.out.println("Name: " + name);
System.out.println("Telephone Number: "+telephoneNo);
System.out.println("Address: "+address);
}