Creating an email and username from the users name and surname? (Java) - java

Right now I am making a small program which should create an email adress and username out of the users actual name. For example, Peter Anderson types his first and last name in two separate text fields, and the program should then return a username and an email adress in two separate textfields, once you press the save button. For example, Peter Anderson gets the username "a13petand" and the email adress "a13petand#test.com" a = autumn, 13 = 2013. It should only take the first 3 letters from first & last name. It should then append the first name, last name, username and email adress to the text area. This is how my code currently looks like;
package test5;
import javax.swing.JOptionPane;
public class Test5 extends javax.swing.JFrame {
String[][] Users = new String[20][4];
int counter;
public Test5() {
initComponents();
}
private void savebtnActionPerformed(java.awt.event.ActionEvent evt) {
if (counter < Users.length) {
Users[counter][0] = Firstnametf.getText();
Users[counter][1] = Lastnametf.getText();
Users[counter][2] = Usernametf.getText();
Users[counter][3] = Emailtf.getText();
jTextArea1.append(Users[counter][0] + ", " + Users[counter][1] + ", " + Users[counter][2] + ", " + Users[counter][3] + "\n");
counter++;
} else {
JOptionPane.showMessageDialog(null, "The array is full!");
counter = Users.length;
}
}
How should I continue from here? How do I make it generate "a13" and then take the first 3 letters in the first and last name? That is my main problem. All I know is that I should use the String class method substring to pick the first 3 letters out of first & last name. And then use the Calendar class to get the correct year. But I don't know how to make it work with my current code, which is the problem.

Date date = Calendar.getInstance().getTime();
String result = "";
result += new SimpleDateFormat("MMM").format(date).substring(0,1).toLowerCase();
result += new SimpleDateFormat("yy").format(date);
result += Firstnametf.getText().subString(0,3);
result += Lastnametf.getText().subString(0,3);

you should use
firstName = Firstnametf.getText().subString(0,3);
lastName = Lastnametf.getText().subString(0,3);
currentYear = Calendar.getInstance().get(Calendar.YEAR);
voila = firstName.concat(lastName).concat(currentYear);
or
voila = firstName + lastName + currentYear.toString ;

Related

How can I make sure that the user did not enter his/her entire name in the First Text Field named as "First Name"

This question says ask for the 'First Name' and the 'Last Name' from the user and then show the message Welcome with the full name of the user . also make sure that the user does not enter his/her full name in the first Text Field which asks for First Name only
I thought that if the user enters his/her full name in the first text field , we can know that from the fact that he/she entered a space or (' ') or not . If not we can simply show the message Welcome + full name . However it didn't work the way I thought it would ... Can somebody help me with itenter image description here
If I understand you the below will work accomplish what you need by ignoring the data after the space and asking the user for their last name.
code:
public static void main(String[] args) {
// Properties
Scanner keyboard = new Scanner(System.in);
String firstName, lastName
// Ask the user for their first name
System.out.println("What is your first name? ");
System.out.print("--> "); // this is for style and not needed
firstName = keyboard.next();
// Ask the user for their last name
System.out.println("What is your last name? ");
System.out.print("--> "); // this is for style and not needed
lastName = keyboard.next();
// Display the data
System.out.println("Your first name is : " + firstName);
System.out.println("Your last name is : " + lastName);
}
There is actually a few ways you can do this, but if I understand your question correctly a simple way would be below, which is from http://math.hws.edu/javanotes/c2/ex6-ans.html and helped me understand Java more when I was learning it, you just would alter it to your needs.
code:
public class FirstNameLastName {
public static void main(String[] args) {
String input; // The input line entered by the user.
int space; // The location of the space in the input.
String firstName; // The first name, extracted from the input.
String lastName; // The last name, extracted from the input.
System.out.println();
System.out.println("Please enter your first name and last name, separated by a space.");
System.out.print("? ");
input = TextIO.getln();
space = input.indexOf(' ');
firstName = input.substring(0, space);
lastName = input.substring(space+1);
System.out.println("Your first name is " + firstName + ", which has "
+ firstName.length() + " characters.");
System.out.println("Your last name is " + lastName + ", which has "
+ lastName.length() + " characters.");
System.out.println("Your initials are " + firstName.charAt(0) + lastName.charAt(0));
}
}
edit:
If this doesn't make sense I can give a better explanation with a better example with more detail.
More notes on similar problems.
https://www.homeandlearn.co.uk/java/substring.html
The problem with your code is, that you check every single charackter and then do the if/else for every single charackter. which means if the last charackter is not a whitespace it will at the end process the else tree.
The solution is to just check once:
if(fn.contains(' '){
//Do what you want to do, if both names were entered in the first field
}else{
//Everything is fine
}

How do write several Java codes using Strings and while loop with JOptionPane

I am in beginning Java. I have been trying for several days to figure how to code the following:
Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane.
In the loop, check if the user selects OK of Cancel without entering data, if so prompt the user until valid data is entered.
Separate the name, phone, and email into separate String variables.
In the loop, check if the name is 10 characters or less, if not, prompt the user until valid data is entered.
If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user.
Display the contents in a JOptionPane using the get methods.
Even if someone can help me with just the "Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane."
and/or
"If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user." code.
I can figure out the rest I'm sure. And yes, I know how to spell Sunflower...the A was on purpose. Thank you to anyone who helps. I really appreciate it!
This is what I have: (the Contact class info is posted below) I am learning how to clean this code up to be more efficient. I was going to delete from about Line 19 on after I figured our how to do the while loop. For now, I get all excited when I actually get a code to work.
import javax.swing.*;
public class TestContact
{
public static void main(String[] args)
{
Contact mycontact = new Contact();
mycontact.setName("Tanya Smith");
mycontact.setPhone("440-226-2866");
mycontact.setEmail("tanya#gmail.com");
JOptionPane.showMessageDialog(null,
"The Contact's information is:\n Name: " + mycontact.getName() +
"\n Phone Number: " + mycontact.getPhone () +
"\n Email: " + mycontact.getEmail());
JOptionPane.showInputDialog(null, "Please enter your Name: " );
while Name.equals()
String Info = JOptionPane.showInputDialog(null, "Please enter you Name, Phone Number and Email");
String[] word = Info.split(" ");
String AllInfo =
Character.toString(word[0].charAt(0)) +
Character.toString(word[1].charAt(0)) +
Character.toString(word[2].charAt(0)) +
Character.toString(word[3].charAt(0));
JOptionPane.showMessageDialog(null, "Your Name: " + word[0] + " " + word[1] +
"\nYour Phone: " + word[2] +
"\nYour Email: " + word[3]);
}
}
I figured out how to do it one way with the Character.toString, but not with using the while loop.
While I don't approve of simply asking for code, you do sound legitimately stuck, and confused. I'm also waiting on a 4 gig transfer over a very slow network connection, so here's a bit to get you started. This should get you most of the way. Next time try to post whatever you came up with, regardless of how off base you think it might be. A least we know you're not just asking for code.
public static void main(String [] args) {
promptForData();
}
public static void promptForData() {
boolean cont = true;
while (cont) {
String input = JOptionPane.showInputDialog("Enter name phone and email space delimited.");
cont = !validData(input);
}
}
public static boolean validData(String input) {
String[] parts = input.split(" ");
if (parts.length != 3) return false;
if (parts[0].length() < 11) return false;
return true;
}
"Even if someone can help me with just the "Use a while loop to ask for name, phone, and email separated by spaces using a single JOptionPane."
Pseudo code
String name;
String phone;
String email;
String input;
String[] array;
while name.length() > 10 or name is null
input = JOptionPane...
array = input.split(....)
name = first array index
// end loop
phone = second array index
email = third array index
""If valid data is entered, create the Contact object using the constructor and name, phone, and email supplied by the user." code."
Pseudo code
class Contact
String name;
String phone;
String email
Contact (constructor taking the three field type arg)
this field = an argument
.... // two more
After the loop from the first part after get the valid input
Contact contact = new Contact( fill in the args)

Trouble Adding String Length

I've been learning Java and for some reason, I'm having a brain fart on how to add two strings together. In the program, I successfully have the program state what the length of the First and Last names are independently. However I would like to have the program also state how many characters there are in the name.
I know that I need to assign the string lengths to an integer variable that can be added together, but I'm just blanking at the moment.
My source code is as follows, thank you for your help!
import java.util.Scanner;
/*
* //Program Name: stringwk7
* //Author's Name: MrShiftyEyes
* //Date: 05-12-2013
* //Description: Prompt for a user name; print initials;
* // print out the reverse name, find the length of the names
*/
/**
*
* #author MrShiftyEyes
*/
public class stringwk7{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Create first name and last name StringBuffers
Scanner input = new Scanner(System.in);
System.out.print("What is your first name? ");
StringBuffer firstName = new StringBuffer(input.nextLine());
System.out.print("What is your last name? ");
StringBuffer lastName = new StringBuffer(input.nextLine());
// Declare two string variables using StringBuffer variables
String fName = new String(firstName);
String lName = new String(lastName);
// Display the users initials
System.out.println("Your initials are: " + firstName.charAt(0) + " " + lastName.charAt(0));
// Displays the user's name in reverse
System.out.println("Your name in reverse is: " + lastName.reverse() + " " + firstName.reverse());
// Length of name
System.out.println("The length of my first name is " + firstName.length());
System.out.println("The length of my last name is " + lastName.length());
// Insert a goodbye into the firstName string and display to user
firstName = firstName.reverse(); // Change firstName back to the initial value
System.out.println(firstName.insert(0, "See ya later, "));
}
}
you just mean the first and last name together?
int fullNameLength = lastName.length() + firstName.length();
System.out.println("The length of my full name is " + fullNameLength);
(firstName + lastName).length()

How to use JOptionPane to display info

I need some help writing a program
Using this code I am able to enter in a track name, artist, etc.
I have a problem that I cannot now show this information in JOptionPane to display all of my info
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TestTrack
{
public static void main(String[] args)
{
Scanner myScan = new Scanner(System.in);
System.out.println("Track name");
String name = myScan.nextLine();
System.out.println("Artist");
String Artist = myScan.nextLine();
System.out.println("Track length seconds");
String seconds = myScan.nextLine();
System.out.println("Album");
String Album = myScan.nextLine();
JOptionPane.showMessageDialog(null,"Trackinfo:")
}
}
So I guess I would want the pop out window to say
Track Name: "blank"
Artist: blank
Another question I have is how to ask this question multiple times by using "while" and asking if I would like to add another track
Sorry if I am using any terminology incorrectly I just started to learn Java
This line: JOptionPane.showMessageDialog(null,"Trackinfo:")
Contains what the pop-up window will contain. You pass in what you want its contents to be as the 2nd parameter, which is currently "Trackinfo".
To incorporate a while loop, you'll have to have a loop control variable, or a condition that will break the loop. In my example I used a string. My example uses a while loop that will continue as long as the string is not equal to "quit".
String test = "";
while( ! test.equals("quit") ) {
//use Scanner to get the next value the user enters
//ask for track info
//display that info in a message box
}
To obtain this:
Note: the texts of the OK and Cancel buttons are localized, if your computer is set to US locale you doesn't see 'Annuler"... ;-)
code this:
int answer = 0;
do {
/*----------------------------------------------------------------------------
Here you put the code which set the variables name, artist, seconds... (1)
----------------------------------------------------------------------------*/
final String title = "Track info";
final String message =
"<html><table>" +
"<tr><td>Track name" + "</td><td>" + name + "</td></tr>" +
"<tr><td>Artist" + "</td><td>" + artist + "</td></tr>" +
"<tr><td>Track length seconds</td><td>" + seconds + "</td></tr>" +
"<tr><td>Album" + "</td><td>" + album + "</td></tr>" +
"</table>";
answer =
JOptionPane.showConfirmDialog(
null, message, title, JOptionPane.OK_CANCEL_OPTION );
} while( answer == JOptionPane.OK_OPTION );
(1) You may choose Scanner or GUI whith JOptionPane.showInputDialog()
JOptionPane.showMessageDialog(null,"Trackinfo:" + "\nArtist: " + Artist + "\nseconds: " + seconds + "\nAlbum: " + Album)
Each '\n' means a new line. for doing this multiple times, you should place your code in a while loop, something like this:
while(!(Artist == "end")) {
//your code
}
Use myScan.next() instead of myScan.nextLine()
To output the information into the Message Dialog, use
String trackInfo = "Track Name: " + name + " | Artist : " +artist+ " | Track Length: " + seconds + " | Album: " + album;
JOptionPane.showMessageDialog(null, trackInfo, "Trackinfo", JOptionPane.INFORMATION_MESSAGE);

How to fix an arrayList?

So arrayLists are a first for me, and as far as I know I've been doing everything correctly and following the examples provided to me by my online course. HOWEVER, for some reason or other I have a line underlined red...which I will get to in a moment after a brief explanation of this program.
This program allows you to input an employee information and after pressing the 'list' button (listButton) it outsput in the employeeField etc etc. That basically sums up this program.
public class EmployeeView extends FrameView {
class Company { //this is the class to allow me to put 'company' in the arrayList...
String ID, firstName, lastName, annualSal, startDate, mileage;
Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) {
ID = _ID;
firstName = _firstName;
lastName = _lastName;
annualSal = _annualSal;
startDate = _startDate;
}
}
/** Define the ArrayList */
ArrayList <Company> inventory = new ArrayList <Company>();
private void AddActionPerformed(java.awt.event.ActionEvent evt) {
String c;
String ID, firstName, lastName, annualSal, startDate;
ID = IDField.getText(); //all this stuff grabs info from the Fields...which will then be stored in the array
firstName = firstNameField.getText();
lastName = lastNameField.getText();
annualSal = annualSalField.getText();
startDate = startDateField.getText();
The two lines below this is the culprit. I suppose "new" is't nessisary but it was there in the example so that's why I am using it...however when I get rid rid of it only 'company' is underlined and the 'c' in the 2nd line is underlined instead of having the entire line underlined. Anyways I hope this is making sense...since its (from what I know of) my only problem.
c = new Company(ID, firstName, lastName, annualSal, startDate);
inventory.add(c);
}
private void ListActionPerformed(java.awt.event.ActionEvent evt) {
String temp="";
for (int x=0; x<=inventory.size()-1; x++) {
temp = temp + inventory.get(x).ID + " "
+ inventory.get(x).firstName + " "
+ inventory.get(x).lastName + " "
+ inventory.get(x).annualSal + " "
+ inventory.get(x).startDate + "\n";
}
employeeTArea.setText(temp);
}
You've declared c to be a String; you can't assign a Company directly to a String.
Change your declaration of c to be Company.
c is declared as a String above. It should be type Company instead.

Categories

Resources