I'm working on a project that requires users input 7 information elements (all at once, separated by commas). If any invalid fields entered, display an message and ask user to input that field again. If all the info. entered correctly. Display all the fields, one field per line with label. Here what I got so far:
import java.util.Scanner;
public class Implementation
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first name: ");
String firstName = scanner.nextLine();
System.out.println("Please enter last name: ");
String lastName = scanner.nextLine();
System.out.println("Please enter address: ");
String address = scanner.nextLine();
System.out.println("Please enter city: ");
String city = scanner.nextLine();
System.out.println("Please enter state: ");
String state = scanner.nextLine();
System.out.println("Please enter zipcode: ");
String zip = scanner.nextLine();
System.out.println("Please enter phone: ");
String phone = scanner.nextLine();
System.out.println("\nValidate Result:");
if (!validateFirstName(firstName))
System.out.println("Invalid first name");
else if (!validateLastName(lastName))
System.out.println("Invalid last name");
else if (!validateAddress(address))
System.out.println("Invalid address");
else if (!valiadteCity(city))
System.out.println("Invalid city");
else if (!validateState(state))
System.out.println("Invalid state");
else if (!validateZip(zip))
System.out.println("Invalid zipcode ");
else if (!validatePhone(phone))
System.out.println("Invalid phone");
else
System.out.println("Valid input. Thank you!");
}
public static boolean validateFirstName(String firstName)
{
return firstName.matches("[A-Z][a-zA-Z]*");
}
public static boolean validateLastName(String lastName)
{
return lastName.matches("[a-zA-z]+(['-][a-zA-Z]+)*");
}
public static boolean validateAddress(String address)
{
return address.matches("\\d+\\s+([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean valiadteCity(String city)
{
return city.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean validateState(String state)
{
return state.matches("([a-zA-Z]+|[a-zA-Z]+\\s[a-zA-Z]+)");
}
public static boolean validateZip(String zip)
{
return zip.matches("\\d{5}");
}
public static boolean validatePhone(String phone)
{
return phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}");
}
}
I'm new to Java and I do not really know what to do for StringTokenizers. The code above I used basic input. However, I wrote a little part for that but do not sure and no idea where to put it.
System.out.println("Enter info. separated by comma: ");
String sentence = scanner.nextLine();
String[] tokens = sentence.split(",");
System.out.printf("Number of elements: %d%nThe tokens are:%n", tokens.length);
for (String token : tokens)
System.out.println(token);
I came up with two problems:
I do not know where/how to do StringTokenizers on my code.
How do I display all the fields if info entered correctly?
It would be nice if you can explain right on my code. Because I'm new and not really sure what to do. Thank you very much!
StringTokenizer uses for splitting the input string into tokens using the specified separator.
For such kind of tasks where you know the sequence of the elements and for each of the elements there are predefined validation I would prefer to avoid using loops.
The main idea of the tasks is firstly to split the input string into the array of elements and then perform validation.
String input = scanner.nextLine();
String[] elements = input.split(',');
if (elements.length != 7) {
System.out.println("Invalid input string");
System.exit(0);
}
String firstName = elements[0];
while (!validateFirstName(firstName)) {
System.out.println("Please enter first name: ");
firstName = scanner.nextLine();
}
String secondName = elements[1];
while (!validateSecondName(secondName)) {
System.out.println("Please enter second name: ");
secondName = scanner.nextLine();
}
// ... The same logic for the other fields.
Related
I am trying to run this code where it reads a file and sorts the words by the tabs in between the words.
File Example
Area Word Area Word Area 1111 Word
public static void start() throws FileNotFoundException {
// Create Empty address book
AddressBook book = new AddressBook();
Scanner scnr = new Scanner(System.in);
String filename = "contacts.txt";
addContactfromFile(book,filename);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
// Insert contacts FEATURE
System.out.println("------------------------INSERTING CONTACT--------------------------------");
int ans = 0;
System.out.println("Would you like to insert a Contact? 1 or 2");
ans = scnr.nextInt();
scnr.nextLine();
if(ans == 1){
System.out.println("What is the First name");
String f = scnr.nextLine();
System.out.println("What is the Last name");
String l = scnr.nextLine();
System.out.println("What is the Number name");
String n = scnr.nextLine();
System.out.println("What is the Address name");
String a = scnr.nextLine();
System.out.println("What is the City name");
String c = scnr.nextLine();
System.out.println("What is the State name");
String s = scnr.nextLine();
System.out.println("What is the Zip Code name");
int z = scnr.nextInt();
book.insertContact(f,l,n,a,c,s,z);
System.out.println("Contact has been added!");
}else {
System.out.println("Ok");
}
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// search FEATURE
System.out.println("------------------------SEARCHING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkSearch(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// delete Contact FEATURE
System.out.println("------------------------DELETING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkDelete(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// Check if address book is empty FEATURE
addContactfromFile(book, "contacts.txt");
System.out.println("Is the Address Book Empty: "+book.isAddressBookEmpty());
System.out.println(book.getNumberOfContacts());
}
public static void checkSearch(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Who would like to look for?'First name'");
String first = scnr.nextLine();
System.out.println("Who would like to look for?'Last name'");
String last = scnr.nextLine();
try{
Contact c = book.searchContact(first,last);
System.out.println(c.getFirstName()+ " " + c.getAddress().getStreet());
}catch (Exception e){
System.out.println(e);
System.out.println("Contact isnt there");
}
}
public static void checkDelete(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter First Name");
String first = scnr.nextLine();
System.out.println("Enter Last Name");
String last = scnr.nextLine();
try{
book.deleteContact(first,last);
}catch (Exception e){
System.out.println(e);
System.out.println("Didnt work");
}
}
public static void addContactfromFile(AddressBook book, String filename) throws NumberFormatException, FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
while(reader.hasNextLine()) {
String contactString = reader.nextLine();
String[] contactElementStrings = contactString.split("\t");
int zipcode = Integer.parseInt(contactElementStrings[5]);
Address address = new Address(contactElementStrings[2],contactElementStrings[3],contactElementStrings[4],zipcode);
Contact contact = new Contact(contactElementStrings[0],contactElementStrings[1],address,contactElementStrings[6]);
book.insertContact2(contact);
}
}
The Error I receive from this is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Helper.addContactfromFile(Helper.java:106)
at Helper.start(Helper.java:16)
at Driver.main(Driver.java:17)
contactElementStrings[5] contains an empty string.
Integer.parseInt(contactElementStrings[5]) is throwing NumberFormatException because an empty string cannot be parsed to an int.
Add a check to see whether contactElementStrings[5] can be parsed to an int.
int zipcode;
if (contactElementStrings.length > 6) {
if (contactElementStrings[5] != null && !contactElementStrings[5].isEmpty()) {
zipcode = Integer.parseInt(contactElementStrings[5]);
}
else {
zipcode = 0;
}
}
EDIT
From your comment, it appears that there are lines that don't contain all the fields that you expect. Hence you also need to check whether the split line contains all the expected parts. I have edited the above code to also check whether the split line contains all the expected parts.
I'm building a phone book program where it asks the user for a set of questions, Q1: Enter your name, Q2: Enter your username, Q3: Enter your number. I'm struggling to include exceptions in my program.
public void Q1(){
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter the name of the person: ");
while (!scan.hasNext()) {
System.out.println("Invalid Input!");
scan.next();
}
firstName = scan.next();
}while(firstName != null);
Q2();
}
Q2(); has practically the same code as Q1();. My problem here is validating user input and moving onto the next question.
Build a method that verifies the string input if empty string entered by the user then print invalid input until getting valid one, and verify the string of the digits using the REGEX \\d+ which means one digit or more, like this:
String name, username;
int number;
public void Q1(Scanner scan) {
System.out.println("Enter the name of the person: ");
name = readAndCheckString(scan);
}
public void Q2(Scanner scan) {
System.out.println("Enter the username of the person: ");
username = readAndCheckString(scan);
}
public void Q3(Scanner scan) {
System.out.println("Enter number of the person: ");
String numberString = readAndCheckDigit(scan);
number = Integer.parseInt(numberString);
}
String readAndCheckString(Scanner scan) {
String input = scan.nextLine();
while ("".equals(input)) {
System.out.println("Invalid Input!");
input = scan.nextLine();
}
return input;
}
String readAndCheckDigit(Scanner scan) {
String numberString = scan.nextLine();
// if numberString is empty or not digit then print invalid
while ("".equals(numberString) || !numberString.matches("\\d+")) {
System.out.println("Invalid Input!");
numberString = scan.nextLine();
}
return numberString;
}
I'm trying to learn the basics of Java when I have nothing to do at work, and I wanted to play around with input. This is what I have now:
import java.util.Scanner;
public class Input {
private static Scanner input;
public static void main(String [] args){
String name = (askName());
double age = (askAge());
System.out.println("Your name is " + name + " and your age is " + age);
}
static String askName(){
System.out.print("What is your name?");
input = new Scanner(System.in);
//listens for strings
String name = input.next();
return name;
}
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
double age = input.nextDouble();
if (input.hasNextDouble()){
return age;
} else {
System.out.println("Please insert a number:");
askAge();}
}
}
And this is what I get:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type double
at Input.askAge(Input.java:16)
at Input.main(Input.java:6)
What do I do to force the user to enter an integer (that is, how do I make the method repeat itself until it gets an int that it can return?)
Return the value of the recursive call:
System.out.println("Please insert a number:");
return askAge();
However: it would be better to use a loop rather than recursion here, since you could (eventually) get a StackOverflowError if you keep on entering an invalid value.
If condition is used for decision making and not for looping.
Use a while loop , Break the loop when u get the correct value.
I am wiring a sudo code.
while(true){
if (input.hasNextDouble()){
//Assign value to a variable ;
//Break loop
} else {
//Re ask question
System.out.println("Please insert a number:");
}
}
Example link for your help.
The exception you are getting is because you are not returning any value from askAge() in else part.
I would rather do it this way:
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String name = getString(sc, "What is your name? ");
int age = getInt(sc, "What is your age? ");
System.out.println("Your name is " + name + " and your age is " + age);
}
/* You increase the performance when using an already existing single
scanner multiple times for different reasons (to get a name, first name,
second name, age, etc.), instead of making a new Scanner each time */
public static String getString(Scanner sc, String message) {
System.out.print(message);
return sc.nextLine();
}
public static int getInt(Scanner sc, String message) {
System.out.print(message);
if (sc.hasNextInt()) {
return sc.nextInt();
} else {
sc.next(); // required to skip the current input
return getInt(sc, "Please insert a number: ");
}
}
Please change your mathod like,
static double askAge(){
System.out.print("What is your age?");
input = new Scanner(System.in);
//listens for doubles
if (input.hasNextDouble()){
return input.nextDouble();
} else {
System.out.println("Please insert a number:");
}
return askAge();
}}
package contractmanager;
import java.util.*;
/**
*
* #author Tom McCloud
*/
public class ContractManager {
static Scanner keyb = new Scanner(System.in);
// global scanner
public static void main(String[] args) {
int option;
//variable declaration
String clientName;
String packageSize;
String dataBundle;
String reference;
int period;
boolean intlCalls;
//display menu to user
System.out.println("Welcome: \n");
System.out.println("1. Enter new contract ");
System.out.println("2. Display contract summary");
System.out.println("3. Display summary of contract for selected month");
System.out.println("4. Find and display contract");
System.out.println("0. Exit");
//take option off user
option = keyb.nextInt();
//WIP - only working on option 1 at the minute
switch(option) {
case 1:
clientName = clientName();
packageSize = packageSize();
dataBundle = dataBundle();
reference = reference();
break;
}
exit();
}
public static void exit()
{
System.out.println("Thank you for using the contract manager. Goodbye!");
}
public static String clientName()
{
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.nextLine();
return name;
}
public static String packageSize()
{
String size;
System.out.println("Please input your package size: ");
System.out.println(" 1. Small \n 2. Medium \n 3. Large");
size = keyb.next();
return size;
}
public static String dataBundle()
{
String data;
System.out.println("Please input data bundle size: ");
System.out.println("1. Low \n 2. Medium \n 3. High \n 4. Unlimited");
data = keyb.next();
return data;
}
public static String reference()
{
String ref;
boolean isRefValid = false;
do {
System.out.println("Please input your reference code: ");
ref = keyb.next();
if(ref.length() > 6)
{
System.out.println("Reference number too long, re-enter!");
}
for(int i = 0; i < 2; i++)
{
if(Character.isDigit(ref.charAt(i)))
{
System.out.println("First two characters must be letters!");
}
}
} while(isRefValid = false);
return ref;
}
}
So, this is some code I have. If I press enter code hereone, it executes these, now technically shouldn't this be in order of one another once each method reaches completion and returns?
For example, on execution after pressing "1" I get the following output:
Please input your full name:
Please input your package size:
1. Small
2. Medium
3. Large
Whereas this should come one by one, after the full name has been inputted it should move onto the package size step. If I input it goes to the third step rather than repeating for the second step's input.
I think it's because in your clientName function you have just printed "Please input your full name: " without waiting for input. For example you have to do something like below here scan.nextLine() will wait until user have press enter:
Scanner scan = new Scanner();
System.out.println("Please input your full name:");
String name= scan.next();
System.out.println(name);
scan.nextLine();
Updated: Try by updating clientName function as below
public static String clientName() {
String name = " ";
System.out.println("Please input your full name: ");
name = keyb.next();
keyb.nextLine();
return name;
}
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);
}