Accept only 8-digit numbers - java

I have this assignment and I need help when I try to change sales value it does not change and when I enter the Id for salesperson must be accept 8 digit numbers not more or less
I tryed .....but I stoped here.
else {
System.out.print("Please enter your ID : ");
String ID = scanner.nextLine();
//Declaration
boolean exists = checkIfIDExists(ID);
if(exists) {
System.out.print("Please enter new sales value : $");
float newSalesValue = scanner.nextFloat();
Iterator<Salesperson> iterator = salespersons.iterator();
while(iterator.hasNext()) {
Salesperson salesperson = iterator.next();
if(salesperson.getID().equals(ID)) {
salesperson.setAnnualSales(newSalesValue);
}
}
}
accapet 8 digit numbers
}
else {
System.out.print("Please enter your ID : ");
String ID = scanner.nextLine();
boolean ifValid = validateID(ID, salespersons);
if(MAX_ID_CHAR_COUNT != ID.toCharArray().length) {
} else {
System.out.print("Please enter eight digits of your ID : ");
ID = scanner.nextLine();
// Declaration and loop
}
//if = validateID(ID, salespersons);
if(ifValid) {
System.out.print("Duplicate digits. Please enter eight digits of your ID : ");
ID = scanner.nextLine();
}

using a loop to validate you id is valid ,that is a code
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
boolean ifValid=false;
String ID;
//using loop to validate this id is valid and length is 8
do{
System.out.print("Please enter your ID : ");
ID = scanner.nextLine();
ifValid= validateID(ID, salespersons);
if (!ifValid){
System.out.print("Duplicate digits. Please enter eight digits of your ID : ");
}
}while (!ifValid);
System.out.print("Please enter eight digits of your ID : ");
ID = scanner.nextLine();
}
private static boolean validateID(String id, Object salespersons) {
return id!=null&&8==id.length();
}

Related

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

Java Do While Validation

How do I change this while(true) into a do while so when the user enters a number they will be given back details but if they enter * the system will close.
while (true){
System.out.print("Enter number: ");
int option = keyboard.nextInt();
out.writeInt(option);
char option;
do {
System.out.print("Enter number: ");
option = keyboard.nextChar();
out.writeChar(option);
} while (option != '*')
You may want to use nextLine() or next() to receive the input and parse them accordingly:
do{
System.out.print("Enter number: ");
String str = keyboard.nextLine();
int option = 0;
if(str.matches"[0-9]+"){
option = Integer.parseInt(str);
System.out.println(option);
}
else if(str.equals("*"))
System.exit(0); //or use break; if you want to exit the loop
}while(whatever); //whatever == true
If you change it to allow the user to input a String and then convert to int if possible, you can catch any errors and break out if the user enters a '*' character:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option;
String input;
do{
System.out.print("Enter number: ");
input = keyboard.nextLine();
try{
option = Integer.parseInt(input);
System.out.println("You entered the value: " + option);
}
catch(Exception ex) {
if (!input.equals("*")){
System.err.println("Invalid input, please enter numbers only.");
}
}
}while(!input.equals("*"));
}
}
If you use an exit value like (-1), you can continue to process input with nextInt() and becomes even easier. You can do this with a simple do/while:
import java.util.*;
class MainInput{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int option = 0;
do{
System.out.print("Enter number: ");
option = keyboard.nextInt();
System.out.println("You entered the value: " + option);
}while(option != -1);
}
}
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
}while(!str.equals("*"))
edit: if you want to play with numbers as integer or double. Just let me know and I'll add casted version as your needs.
int number;
do{
System.out.print("Enter number: ");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
number = Integer.parseInt(str);
}while(!str.equals("*"))
now you have a integer number.

Missing order of display in console when using scanner in java

My code is,
public class trueFalse {
public static void main(String[] args){
String sz = null;
do{
String s = null;
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();
if(myint<0){
System.out.println("Lessthan zero");
}
else
{
s = getVal(myint);
System.out.println("Value :: "+s);
}
Scanner keyboard2 = new Scanner(System.in);
System.out.println("Do you want to continue ? (YES/no)");
sz = keyboard2.next();
}while(sz.equalsIgnoreCase("yes"));
}
public static String getVal(int num){
return num == 0 ? "ZERO" : "One+";
}
}
When I execute the display order in console as follows,
enter an integer
Value :: One+
Do you want to continue ? (YES/no)
1 #[this one I entered second line in console]
yes
enter an integer
Value :: One+
Do you want to continue ? (YES/no)
3
enter an integer
yes
Where I made mistake ?
There is no need to use two Scanners. You can replace sz = keyboard2.next(); with sz = keyboard.nextLine(); Also, move the Scanner outside your do-while loop.
Also, you'll have to add keyboard.nextLine(); after int myint = keyboard.nextInt();
Here is the corrected code snippet:
public static void main(String[] args) {
/* Move Scanner outside of do-while */
Scanner keyboard = new Scanner(System.in);
String s = null;
String sz = null;
do {
System.out.println("Enter Integer Value: ");
/* Integer Parsing */
String str = keyboard.nextLine();
System.out.println("Entered Integer: " + str);
int myint = Integer.parseInt(str);
if(myint < 0){
System.out.println("Value Less Than Zero!");
}
else
{
s = getVal(myint);
System.out.println("Value :: " + s);
}
System.out.println("Do you want to continue ? (yes/no)");
sz = keyboard.nextLine();
System.out.println("Entered Value: " + sz);
} while(sz.equalsIgnoreCase("yes"));
}
public static String getVal(int num){
return num == 0 ? "ZERO" : "One+";
}
Output:
Enter Integer Value:
Entered Integer: 1
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: yes
Enter Integer Value:
Entered Integer: 2
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: yes
Enter Integer Value:
Entered Integer: 3
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: yes
Enter Integer Value:
Entered Integer: 4
Value :: One+
Do you want to continue ? (yes/no)
Entered Value: no

Two methods executing at the same time? Why?

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

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