Inputting and validating the email address in JAVA - java

I have written the below code but i am unable to make it loop if the input entered is false.Kindly help me.
System.out.println("Please enter your email address ex:xyz#gmail.com");
String emailaddress=name.nextLine();
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = emailaddress;
Boolean b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
System.out.println("Email address is " +emailaddress);

Here goes the 3 functions :
public class abc{
public static void main(String[] args){
inputEmail();
}
public boolean checkEmailvalidity(String emailaddress){
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
boolean b = testString.matches(email_regex);
return b;
}
public void inputEmail(){
System.out.println("Please enter your email address ex:xyz#gmail.com");
String emailaddress=name.nextLine();
boolean a = checkEmailvalidity(emailaddress);
if(a){
System.out.println("Valid email");
} else {
System.out.println("InValid email");
inputEmail();
}
}
}
here is with your updated answer :
package smsmain;
import java.util.Scanner;
public class CStudentinfo {
public static void createstudent() {
Scanner name = new Scanner(System.in);
System.out.println("Please enter your first name:");
while(!name.hasNext("[a-zA-Z]+")){
System.out.println("Please re-enter your name, use alphabets)
System.out.println("Please enter your first name:");
name.nextLine();
}
String firstname=name.nextLine();
System.out.println("Your firstname is " + firstname);
inputEmail();

boolean b;
do {
System.out.println("Please enter your email address ex:xyz#gmail.com");
String emailaddress=name.nextLine();
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = emailaddress;
b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
System.out.println("Email address is " +emailaddress);
}while(!b);

String testString;
String emailaddress;
boolean b = false;
do {
System.out.println("Please enter your email address ex:xyz#gmail.com");
Scanner name = new Scanner(System.in);
emailaddress = name.nextLine();
String email_regex = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
testString = emailaddress;
b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
} while (!b);
System.out.println("Email address is " + emailaddress);

Related

Can i take userinput in a method java class?

public static void userinput() {
System.out.print("Enter your name : ");
Scanner d = new Scanner(System.in);
String username = d.next();
System.out.print("\nEnter your Age : ");
Scanner a = new Scanner(System.in);
int Age = a.nextInt();
System.out.print("\nEnter your roll number : ");
Scanner b = new Scanner(System.in);
int rollno = b.nextInt();
System.out.print("\nEnter your city : ");
Scanner c = new Scanner(System.in);
String city = c.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
return (0);
}
Is this the correct way to take input from a user in the method?
Here is the corrected version :
public static void userinput() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name : ");
String username = sanner.nextLine();//as next() reads only a word
System.out.print("\nEnter your Age : ");
int age = Integer.parseInt(scanner.nextLine());//as nextInt() does not read the \n which may cause next string inputs to be null
System.out.print("\nEnter your roll number : ");
int rollno = Integer.parseInt(scanner.nextLine());
System.out.print("\nEnter your city : ");
String city = scanner.nextLine();
System.out.println("Hello, " + username + " your age is " + Age + " you live in " + city + " and your roll number is " + rollno);
//a void function doesn't compulsorily need a return statement
}
Also only one Scanner is enough!

How to get number from file that is written

I am making an java program for college and I am stuck at one point, the exam says I need to extract information from an txt file that is already written. I need to get only the information from the end of the lines like password or something.
DISCLAIMER:
I know how to do it by using scanner and file. But it is not really clear how to extract only the information not the whole line.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Trip {
private String password;
private String placeOfDeparture;
private String destination;
private int durationInDays;
private double wage;
private double rentPrice;
private String firstName;
private String lastName;
private String[] passwords;
public Trip(String placeOfDeparture, String destination, int durationInDays, double wage,
double rentPrice, String firstName, String lastName) {
super();
this.placeOfDeparture = placeOfDeparture;
this.destination = destination;
this.durationInDays = durationInDays;
this.wage = wage;
this.rentPrice = rentPrice;
this.firstName = firstName;
this.lastName = lastName;
generateTripPassword();
}
public void generateTripPassword() {
Random rand = new Random();
int randomNumbers = rand.nextInt(100);
String personInitials = "";
String departureInitials = "";
String destinationInitials = "";
personInitials += firstName.substring(0, 1).toUpperCase();
personInitials += lastName.substring(0, 1).toUpperCase();
departureInitials += placeOfDeparture.substring(0, 2).toUpperCase();
destinationInitials += destination.substring(0, 2).toUpperCase();
for(int i = 0; i < passwords.length; i++) {
if(passwords[i] == null) {
passwords[i] = personInitials + departureInitials + destinationInitials + randomNumbers;
break;
}
}
this.password = personInitials + departureInitials + destinationInitials + randomNumbers;
}
public void getTripInformation() {
System.out.println("Trip details: \n");
System.out.println("Trip password: " + password);
System.out.println("Passenger name: " + firstName + " " + lastName + ".");
System.out.println("Duration in days: " + durationInDays + ".");
System.out.println("Wage: " + wage + ".");
System.out.println("Rent price is: " + rentPrice + ".");
}
public void writeTripInfo(String tripType) {
File file = new File(this.password + ".txt");
try {
FileWriter trip = new FileWriter(file);
trip.write("Trip details: ");
trip.write("Trip password: " + password);
trip.write("Passenger name: " + firstName + " " + lastName + ".");
trip.write("Duration in days: " + durationInDays + ".");
trip.write("Wage: " + wage + ".");
trip.write("Rent price is: " + rentPrice + ".");
trip.write("Type of the trip is: " + tripType);
trip.close();
System.out.println("File writing successfully completed! Name of yje file is: " + this.password + " . Enjoy.");
} catch (IOException e) {
System.out.println("An error occured while writing file.");
System.out.println("Here is the error debug code: ");
e.printStackTrace();
}
}
}
After you have put each part on its own line (and removed the '.' at the end), you can parse each line by splitting on ':'
public void readTripInfo(String path)
{
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
// Read each line of file
while ((line = br.readLine()) != null) {
// Split on ':'
String [] parts = line.split(":");
if (parts.length == 2) {
// Save
if (parts[0].equals("Trip password")) {
password = parts[1].trim();
}
else if (parts[0].equals("Passenger name")) {
String [] names = parts[1].trim().split(" ");
if (names.length == 2) {
firstName = names[0];
lastName = names[1];
}
}
else if (parts[0].equals("Duration in days")) {
durationInDays = Integer.parseInt(parts[1].trim());
}
// Continue for the rest
}
}
}
catch (Exception e) {
System.out.println(e);
}
}

How to fix it ? i am very very new to java

package app;
import java.util.Scanner;
import java.util.UUID;
public class AccountThis {
private static Scanner scanner;
public static void main( String[] args ) {
//name input
scanner = new Scanner( System.in );
System.out.print( "Type your name: " );
String nameInput = scanner.nextLine();
System.out.println("Hello" + " " + nameInput);
//deposit input
scanner = new Scanner( System.in );
System.out.print( "Type how much you want to deposit:" );
double depositInput = scanner.nextDouble();
System.out.println("you want to deposit" + " " + depositInput + "$");
public AccountThis(String id) {
System.out.println("ID Generated"
+ "Please Write it down :" + id);
}
class RandomStringUUID {}
public id = randID;{
UUID randID = UUID.randomUUID();
UUID randomUUIDString = randID;
System.out.println(randomUUIDString );
new AccountThis( nameInput, depositInput, id);
}
{
}
}
public AccountThis() {
System.out.println( "created an account." );
}
public AccountThis( String nameInput ) {
System.out.println( " created account with name " + nameInput );
}
public AccountThis(double depositInput) {
System.out.println(depositInput + "$" + "added to your account!" );
}
}
i am new to java and i am trying to get id and assign it to the console with some text as you can see i failed a little bit if you can help me figure it out i would be very very happy
btw i called it id cause i set on it all night and couldn't figure it out.
Try this code. It is working fine
import java.util.Scanner;
import java.util.UUID;
public class AccountThis {
private static Scanner scanner;
public AccountThis(String nameInput) {
System.out.println(" created account with name " + nameInput);
}
public AccountThis() {
System.out.println("created an account.");
}
public AccountThis(double depositInput) {
System.out.println(depositInput + "$" + "added to your account!");
}
public AccountThis(String nameInput, double depositInput, String id) {
System.out.println(" created account with \n ID : " + id + ", \n name : " + nameInput);
System.out.println(depositInput + "$" + "added to your account!");
}
public static void main(String[] args) {
//name input
scanner = new Scanner(System.in);
System.out.print("Type your name: ");
String nameInput = scanner.nextLine();
System.out.println("Hello" + " " + nameInput);
//deposit input
scanner = new Scanner(System.in);
System.out.print("Type how much you want to deposit:");
double depositInput = scanner.nextDouble();
System.out.println("you want to deposit" + " " + depositInput + "$");
UUID randID = UUID.randomUUID();
String id=randID.toString();
new AccountThis(nameInput, depositInput,id);
}
}

Program Runs but No Output?

Sorry, I'm a bit clueless when it comes to this and I'm having a bit of trouble with this specific portion of my program.
The goal is, when someone inputs a three word string, to rearrange it in such a way that "Emma Charlotte Leonard" becomes " Leonard, Emma, C".
This is what I have so far for that specific method:
public String lastFirst (String str)
{
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String lastFirst = keyboard.nextLine();
String middleAndLast = lastFirst.substring(lastFirst.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = lastFirst.substring(0, lastFirst.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
Any help would be appreciated, sorry if I haven't put enough information.
I believe this is what you are trying to achieve:
public class RearrangeName{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter your name");
String inputStr= keyboard.nextLine();
System.out.println(lastFirst(inputStr));
}
public static String lastFirst (String str){
String middleAndLast = str.substring(str.indexOf(" ")+ 1);
String last = middleAndLast.substring(middleAndLast.indexOf(" ") + 1);
String first = str.substring(0, str.indexOf(" "));
String middle = middleAndLast.substring(0, middleAndLast.indexOf(" "));
char middleInitial = middle.charAt(0);
return("\"" + last + ", " + first + ", " + middleInitial + "\"");
}
}
See the Demo here
Do you want output to be "Leonard, Charlotte, L" or "Leonard, Emma, C".
Current output of your program is the second option. And if you desired first output then you should declare middleInitial as String middleInitial =last.charAt(0);.
Try following example it is return the "Emma Charlotte Leonard" as " Leonard, Charlotte, L"
public class Example{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Example exp = new Example();
System.out.print("Enter your number : ");
System.out.println(exp.getName(input.nextLine()));
}
private String getName(String name){
String arr[] = name.split(" ");
return arr[2]+ ", "+arr[1]+", "+arr[2].substring(0, 1);
}
}

Get method returns null

So I tried to make a Hanger program in Java, and when I try to get to output a variable using a get method, it returns null. I first set up a Scanner object, then I set a String to the value the user inputs, then I use a set method to set the String to a new variable, finally, I call that new variable using the get method. It returns null, and I don't know why.
import java.util.Scanner;
public class Hanger
{
public String word;
public Hanger(){}
public void setWord(String new_word)
{
new_word = word;
}
public String getWord()
{
return word;
}
public static void main(String[] args)
{
Scanner input_names = new Scanner(System.in);
Scanner input_word = new Scanner(System.in);
Hanger word1 = new Hanger();
System.out.println("Please enter Player 1's name.");
String name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
String name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
String names_correct = input_names.nextLine();
switch (names_correct)
{
case "no":
{
System.out.println("Please enter Player 1's name.");
name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
names_correct = input_names.nextLine();
}
case "No":
{
System.out.println("Please enter Player 1's name.");
name1 = input_names.nextLine();
System.out.println("Please enter Player 2's name.");
name2 = input_names.nextLine();
System.out.println("Are your names " + name1 + " and " + name2 + "?");
names_correct = input_names.nextLine();
}
default:
{
break;
}
}
System.out.println("Let's begin! " + name1 + ", please type a word that " + name2 + " will try to guess.");
String input_word1 = input_word.nextLine();
word1.setWord(input_word1);
System.out.println("Is " + word1.getWord() + " correct?");
}
}
It should be this.word=new_word in your setWord method of Hanger class

Categories