How to add multiple user-prompts in while loop? - java

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);
}

Related

This is 2d string array I want search details using id how i can do

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");
}
}

How to validating user input with hasNext(); while?

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;
}

used of loop and encapsulation

I'm trying to get the program to do:
If the data entered is not accepted, request the information again
(note: it is fine to request ALL the information again, it is not necessary to only request specific info to be re-entered, but you can if you would like).
For the program everything seem to run fine except for when its the resolution, it ask for another input but if the input isn't correct it just accept. I need it to keep running until the correct input is enter.
import java.util.Scanner;
public class encap
{
private static String userID;
private static String password;
private static String resolution;
private static int Ramsize;
private static int freespace;
private static int videocard;
//Get and Set methods
public static String getuserID()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter userID : ");
userID = input.next();
return userID;
}
public static String getpassword()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter password : ");
password = input.next();
return password;
}
public static String getresolution()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter video resolution: ");
resolution = input.next();
if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900"));
else
{
while(true)
{
System.out.println("Information invalid, Please fill again");
String getresolution = input.next();
if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900"));
break;
}
}
return resolution;
}
public static int getRamsize()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter RAM size : ");
while(true)
{
if(input.hasNextInt())
{
Ramsize = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter RAM size : ");
}
}
return Ramsize;
}
public static int getfreespace()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter HD free space : ");
while(true)
{
if(input.hasNextInt())
{
freespace = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter HD free space : ");
}
}
return freespace;
}
public static int getvideocard()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter video card RAM size: ");
while(true)
{
if(input.hasNextInt())
{
videocard = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter video card RAM size: ");
}
}
return videocard;
}
public static void setuserID(String newuserID)
{
userID = newuserID;
}
public static void setpassword(String newpassword)
{
password = newpassword;
}
public static void setresolution(String newresolution)
{
resolution = newresolution;
}
public static void setRamsize (int newRamsize)
{
Ramsize = newRamsize;
}
public static void setfreespace (int newfreespace)
{
freespace = newfreespace;
}
public static void setvideocard (int newvideocard)
{
videocard = newvideocard;
}
public static void main(String[] args)
{
setuserID(getuserID());
setpassword(getpassword());
setresolution(getresolution());
setRamsize(getRamsize());
setfreespace(getfreespace());
setvideocard(getvideocard());
System.out.println("You have input the following information: " + "\nuserID: " + userID
+ "\npassword: " + password + "\nVideo resolution: " + resolution + "\nRam Size: "
+ Ramsize + "\nHD Free Space: " + freespace + "\nVideo Card Ram Size: " + videocard);
}
}
The problem is because you never do anything within your valid case scenario and you are using .next() for a single character instead of .nextLine() which grabs the entire input entered following an end of line character (return character)
This will ask until the input entered satisfies your if condition.
public static String getresolution()
{
String resolution;
boolean validAnswer = false;
Scanner input = new Scanner(System.in);
HashSet<String> validResolutions = new HashSet<>();
validResolutions.add("800x600");
validResolutions.add("1024x768");
validResolutions.add("1152x900");
//add more resolutions if you want without having to create a bigger if check
//validResolutions.add("1400x1120");
do {
System.out.print("Please enter video resolution: ");
resolution = input.nextLine().replaceAll(" ", "").replaceAll("\n", "");
validAnswer = validResolutions.contains(resolution) ? true : false;
if(!validAnswer)
System.out.println("Incorrect resolution please try again");
} while (!validAnswer);
return resolution;
}

Checking text in file comparing it to user input

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();
}
}

StringTokenizers for Java with regular expression

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.

Categories